path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
information/blendle-frontend-react-source/app/components/PortalTooltip.js
BramscoChill/BlendleParser
import React from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import PortalMixin from 'components/mixins/PortalMixin'; import classNames from 'classnames'; import getScrollParent from 'helpers/getScrollParent'; import Pointer from './Pointer'; const PortalTooltip = createReactClass({ displayName: 'PortalTooltip', propTypes: { pointerSize: PropTypes.number, position: PropTypes.oneOf(['top', 'bottom', 'left', 'right']), layout: PropTypes.string, name: PropTypes.string, onScroll: PropTypes.func, className: PropTypes.string, onMouseEnter: PropTypes.func, truncate: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]), }, mixins: [PortalMixin('tooltip-portal')], getInitialState() { return { pos: { x: 0, y: 0, maxHeight: window.innerHeight, yPos: 'bottom', xPos: 'left', }, truncateCount: null, }; }, getDefaultProps() { return { truncate: false, truncateMessage: null, pointerSize: 5, }; }, render() { return <span />; }, componentDidMount() { this._updatePosition(); if (this.props.onScroll) { this._scrollParent = getScrollParent(ReactDOM.findDOMNode(this)); this._scrollParent.addEventListener('scroll', this.props.onScroll); } }, componentWillUnmount() { if (this.props.onScroll) { this._scrollParent.removeEventListener('scroll', this.props.onScroll); } }, _updatePosition() { const position = this._getPosition(); if (this.props.truncate) { this._truncateChildren(position.maxHeight); } this.setState({ pos: position, }); }, _getPosition() { const target = ReactDOM.findDOMNode(this).parentNode.getBoundingClientRect(); const viewport = { width: window.innerWidth, height: window.innerHeight, }; // fetch tooltip dimensions including the margin const ttBounds = this.getLayerDOMNode().getBoundingClientRect(); const ttStyle = window.getComputedStyle(this.getLayerDOMNode()); const ttMargin = { // only accepts px values x: parseInt(ttStyle.marginLeft, 0) + parseInt(ttStyle.marginRight, 0), y: parseInt(ttStyle.marginTop, 0) + parseInt(ttStyle.marginBottom, 0), }; const tooltip = { width: ttBounds.width + ttMargin.x, height: ttBounds.height + ttMargin.y, }; const pos = this._getFitPosition(target, viewport, tooltip); // calculate maxHeight to be able to truncate content pos.maxHeight = viewport.height - pos.y - ttMargin.y; return pos; }, _getFitPosition(target, viewport, tooltip) { // find out on what place the tooltip will fit const fits = { top: target.top - tooltip.height > 0, bottom: target.top + target.height + tooltip.height < viewport.height, left: target.left - tooltip.width > 0, right: target.right + target.width + tooltip.width < viewport.width, }; // calculate the xy position of the tooltip let x; let xPos; if (fits.right) { x = target.left; xPos = 'right'; } else if (fits.left) { x = target.left - tooltip.width + target.width; xPos = 'left'; } else { x = target.left - tooltip.width / 2 + target.width / 2; xPos = 'center'; } let y; let yPos; const position = this.props.position; if (position && fits[position]) { y = target[position] + tooltip.height * (position === 'top' ? -1 : 1); yPos = position === 'top' ? 'above' : 'below'; } // If it didn't fit on the preferred possition, use the regular calculation if (!y || !yPos) { if (!fits.bottom && fits.top) { y = target.top - tooltip.height; yPos = 'above'; } else { y = target.top + target.height; yPos = 'below'; } } return { x: Math.round(x), y: Math.round(y), xPos, yPos, }; }, _truncateChildren(maxHeight) { if (this.state.truncateCount !== null) { return; } const tooltip = this.getLayerDOMNode(); const children = Array.from(tooltip.children); let top = 0; let truncateCount = 0; let lastVisibleChildIndex = 0; children.forEach((child, index) => { if (top > maxHeight) { truncateCount++; } else { top = child.offsetHeight + child.offsetTop; if (top > maxHeight) { truncateCount++; } } if (truncateCount === 0) { lastVisibleChildIndex = index; } }); // if we hide one item, we also want to hide the last visible item when we want to show a truncate message if (truncateCount && typeof this.props.truncate === 'function') { truncateCount++; } this.setState({ truncateCount }); }, _getPointerOffset(pointerWidth) { const target = ReactDOM.findDOMNode(this).parentNode; return Math.round(target.offsetWidth / 2 - pointerWidth); }, renderLayer() { const className = classNames([ 'v-portal-tooltip', `pos-${this.state.pos.xPos}`, `pos-${this.state.pos.yPos}`, { [`l-${this.props.layout}`]: this.props.layout }, { [`tooltip-${this.props.name}`]: this.props.name }, { [this.props.className]: this.props.className }, ]); const portalStyles = { position: 'fixed', zIndex: 100000, left: `${this.state.pos.x}px`, top: `${this.state.pos.y}px`, maxHeight: `${this.state.pos.maxHeight}px`, }; const tooltipStyles = {}; let truncate; if (typeof this.props.truncate === 'function' && this.state.truncateCount) { truncate = this.props.truncate(this.state.truncateCount); } let pointer; if (this.props.pointerSize) { pointer = ( <Pointer position={this.state.pos.yPos === 'above' ? 'bottom' : 'top'} direction={this.state.pos.xPos} offset={this._getPointerOffset(this.props.pointerSize)} width={this.props.pointerSize} /> ); if (this.state.pos.yPos === 'above') { tooltipStyles.marginBottom = `${3 + this.props.pointerSize}px`; } else { tooltipStyles.marginTop = `${3 + this.props.pointerSize}px`; } } const lastVisibleChildIndex = this.props.children.length - (this.state.truncateCount || 0); return ( <div className={className} style={portalStyles} onMouseEnter={this.props.onMouseEnter} onMouseLeave={this.props.onMouseLeave} > {pointer} <div className="tooltip" style={tooltipStyles}> {this.props.children.slice(0, lastVisibleChildIndex)} {truncate} </div> </div> ); }, }); export default PortalTooltip; // WEBPACK FOOTER // // ./src/js/app/components/PortalTooltip.js
src/shared/views/plans/plan/Plan/Plan.js
in-depth/indepth-demo
import React from 'react' import { Link } from 'react-router' import { PlanAges, PlanInterests, PlanTime } from '../index' import { ButtonRaised } from '../../../../components' import styles from './Plan.css' const Plan = (props) => { return ( <div className={styles.main}> <div className={styles.header}> <h1>Plan</h1> </div> <p className={styles.intro}> {'Give us a few details and we\'ll create the perfect plan for your experience'} </p> <div className={styles.preferencesWrapper}> <div className={styles.preferences}> <PlanTime max={7} min={1} step={1} value={props.preferences.time} action={props.actions.addTime} /> <PlanAges ages={props.preferences.ages} action={props.actions.toggleCheckedAges} /> <PlanInterests interests={props.preferences.interests} action={props.actions.toggleCheckedInterests} /> <Link className={styles.continue} to={`${props.path}/map`}> <ButtonRaised width="300px" label="MAKE MY PLAN" /> </Link> </div> </div> </div> ) } Plan.propTypes = { preferences: React.PropTypes.shape({ time: React.PropTypes.number.isRequired, ages: React.PropTypes.array.isRequired, interests: React.PropTypes.array.isRequired, }).isRequired, actions: React.PropTypes.shape({ addTime: React.PropTypes.func.isRequired, toggleCheckedAges: React.PropTypes.func.isRequired, toggleCheckedInterests: React.PropTypes.func.isRequired, }).isRequired, path: React.PropTypes.string.isRequired, } export default Plan
client/src/app/components/voice-control/components/SpeechButton.js
zraees/sms-project
import React from 'react' import {Popover, OverlayTrigger} from 'react-bootstrap' import {bindActionCreators} from 'redux' import * as VoiceActions from '../VoiceActions' import {connect} from 'react-redux'; import SpeechHelp from './SpeechHelp' class SpeechButton extends React.Component { hidePopover = ()=> { this.refs.vpOverlay.hide() }; render() { const popover = ( <Popover ref="popover" id="popover-basic" placement="bottom" title={null} >{ !this.props.hasError ? <h4 className="vc-title">Voice command activated <br /> <small>Please speak clearly into the mic</small> </h4> : <h4 className="vc-title-error text-center"> <i className="fa fa-microphone-slash"/> Voice command failed <br /> <small className="txt-color-red">Must <strong>"Allow"</strong> Microphone</small> <br /> <small className="txt-color-red">Must have <strong>Internet Connection</strong> </small> </h4> } <div> <a className="btn btn-success" id="speech-help-btn" onClick={this.props.voiceControlShowHelp}>See Commands</a> <a className="btn bg-color-purple txt-color-white" onClick={this.hidePopover}>Close Popup</a> </div> </Popover> ) return ( <div id="speech-btn" className={this.props.className}> <div> <OverlayTrigger trigger={this.props.started ? null : "click" } placement="bottom" ref="vpOverlay" overlay={popover}> <a onClick={this.voiceControlToggle} title="Voice Command" id="voice-command-btn"><i className="fa fa-microphone"/></a> </OverlayTrigger> </div> <SpeechHelp showHelp={this.props.showHelp} onHide={this.props.voiceControlHideHelp}/> </div> ) } voiceControlToggle = (e)=> { if (this.props.started) { this.hidePopover(); this.props.voiceControlOff() } else { this.props.voiceControlOn() } } } export default connect( (state)=> { return state.voice }, (dispatch)=> { return bindActionCreators(VoiceActions, dispatch) } )(SpeechButton)
src/svg-icons/hardware/scanner.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareScanner = (props) => ( <SvgIcon {...props}> <path d="M19.8 10.7L4.2 5l-.7 1.9L17.6 12H5c-1.1 0-2 .9-2 2v4c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-5.5c0-.8-.5-1.6-1.2-1.8zM7 17H5v-2h2v2zm12 0H9v-2h10v2z"/> </SvgIcon> ); HardwareScanner = pure(HardwareScanner); HardwareScanner.displayName = 'HardwareScanner'; HardwareScanner.muiName = 'SvgIcon'; export default HardwareScanner;
asset/assets/jquery-ui/ui/jquery.ui.dialog.js
qwords/evote
/*! * jQuery UI Dialog 1.9.0 * http://jqueryui.com * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/dialog/ * * Depends: * jquery.ui.core.js * jquery.ui.widget.js * jquery.ui.button.js * jquery.ui.draggable.js * jquery.ui.mouse.js * jquery.ui.position.js * jquery.ui.resizable.js */ (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.0", 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 = ( 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" ), uiDialogContent = 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" ) .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 ), uiDialogTitlebarCloseText = ( 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" ), uiButtonSet = ( 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.uiDialog.hide( 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 uiDialogButtonPane, uiButtonSet, 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 ) { props = $.isFunction( props ) ? { click: props, text: name } : props; var button = $( "<button type='button'>" ) .attr( props, true ) .unbind( "click" ) .click(function() { props.click.apply( that.element[0], arguments ); }) .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.join( " " ), at: myAt.join( " " ), offset: offset.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 ( $.browser.msie ) { 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 ( $.browser.msie ) { 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 ) );
ajax/libs/yui/3.18.1/scrollview-base/scrollview-base-coverage.js
jonobr1/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":1457,"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 {Object} 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 {EventFacade} 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 {EventFacade} 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 {EventFacade} 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 {EventFacade} 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 {EventFacade} 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 {EventFacade} 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 {Boolean} 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 {EventFacade} 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 {EventFacade} The event facade"," * @protected"," */"," _afterFlickChange: function (e) {"," this._bindFlick(e.newVal);"," },",""," /**"," * After listener for changes to the disabled attribute"," *"," * @method _afterDisabledChange"," * @param e {EventFacade} 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 {EventFacade} The event facade"," * @protected"," */"," _afterAxisChange: function (e) {"," this._cAxis = e.newVal;"," },",""," /**"," * After listener for changes to the drag attribute"," *"," * @method _afterDragChange"," * @param e {EventFacade} The event facade"," * @protected"," */"," _afterDragChange: function (e) {"," this._bindDrag(e.newVal);"," },",""," /**"," * After listener for the height or width attribute"," *"," * @method _afterDimChange"," * @param e {EventFacade} The event facade"," * @protected"," */"," _afterDimChange: function () {"," this._uiDimensionsChange();"," },",""," /**"," * After listener for scrollEnd, for cleanup"," *"," * @method _afterScrollEnd"," * @param e {EventFacade} 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});
src/svg-icons/action/restore-page.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionRestorePage = (props) => ( <SvgIcon {...props}> <path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm-2 16c-2.05 0-3.81-1.24-4.58-3h1.71c.63.9 1.68 1.5 2.87 1.5 1.93 0 3.5-1.57 3.5-3.5S13.93 9.5 12 9.5c-1.35 0-2.52.78-3.1 1.9l1.6 1.6h-4V9l1.3 1.3C8.69 8.92 10.23 8 12 8c2.76 0 5 2.24 5 5s-2.24 5-5 5z"/> </SvgIcon> ); ActionRestorePage = pure(ActionRestorePage); ActionRestorePage.displayName = 'ActionRestorePage'; ActionRestorePage.muiName = 'SvgIcon'; export default ActionRestorePage;
ajax/libs/reactive-elements/0.4.4/reactive-elements.js
cdnjs/cdnjs
!function(w){w.require&&(React=require("react"));var PROPERTY_DELIMITER_CHARACTERS=[":","-","_"],registrationFunction=(document.registerElement||document.register).bind(document);if(void 0!==registrationFunction){var registerReact=function(e,t){var r=Object.create(HTMLElement.prototype);r.createdCallback=function(){this._content=getContentNodes(this);var e=React.createElement(t,getAllProperties(this,this.attributes));this.reactiveElement=React.render(e,this),extend(this,this.reactiveElement),getterSetter(this,"props",function(){return this.reactiveElement.props},function(e){this.reactiveElement.setProps(e)})},r.attributeChangedCallback=function(e,t,r){this.reactiveElement.props=getAllProperties(this,this.attributes),this.reactiveElement.forceUpdate(),void 0!==this.reactiveElement.attributeChanged&&this.reactiveElement.attributeChanged.bind(this)(e,t,r)},registrationFunction(e,{prototype:r})};document.registerReact=registerReact,void 0!==w.xtag&&(w.xtag.registerReact=registerReact);var extend=function(e,t){for(var r in t)void 0===e[r]&&(e[r]="function"==typeof t[r]?t[r].bind(t):t[r])},getContentNodes=function(e){for(var t=document.createElement("content");e.childNodes.length;)t.appendChild(e.childNodes[0]);return t},getAllProperties=function(e,t){for(var r={},n=0;n<t.length;n++){var i=t[n],o=attributeNameToPropertyName(i.name);r[o]=parseAttributeValue(t[n].value)}return r._content=e._content,r},attributeNameToPropertyName=function(e){for(var t=e.replace("x-","").replace("data-",""),r=-1;-1!==(r=getNextDelimiterIndex(t));)t=t.slice(0,r)+t.charAt(r+1).toUpperCase()+t.slice(r+2,t.length);return t},getNextDelimiterIndex=function(e){for(var t=-1,r=0;r<PROPERTY_DELIMITER_CHARACTERS.length;r++){var n=PROPERTY_DELIMITER_CHARACTERS[r];if(t=e.indexOf(n),-1!==t)break}return t},parseAttributeValue=function(value){var regexp=/\{.*?\}/g,matches=value.match(regexp);return null!==matches&&void 0!==matches&&matches.length>0&&(value=eval(matches[0].replace("{","").replace("}",""))),value},getterSetter=function(e,t,r,n){Object.defineProperty?Object.defineProperty(e,t,{get:r,set:n}):document.__defineGetter__&&(e.__defineGetter__(t,r),e.__defineSetter__(t,n)),e["get"+t]=r,e["set"+t]=n};module.exports=registerReact}}(window),Function.prototype.bind||(Function.prototype.bind=function(e){if("function"!=typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var t=Array.prototype.slice.call(arguments,1),r=this,n=function(){},i=function(){return r.apply(this instanceof n&&e?this:e,t.concat(Array.prototype.slice.call(arguments)))};return n.prototype=this.prototype,i.prototype=new n,i});
src/react/shared/router-context.js
framework7io/Framework7
import React from 'react'; const RouterContext = React.createContext({ route: null, router: null, }); export { RouterContext };
src/docs/examples/TextInputStyledComponents/errorExample.js
choudlet/ps-react-choudlet
import React from 'react'; import TextInputStyledComponents from 'ps-react/TextInputStyledComponents'; /** Required TextBox with error */ export default class ExampleError extends React.Component { render() { return ( <TextInputStyledComponents htmlId="example-optional" label="First Name" name="firstname" onChange={() => {}} required error="First name is required." /> ) } }
src/PageItem.js
Lucifier129/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import SafeAnchor from './SafeAnchor'; const PageItem = React.createClass({ propTypes: { href: React.PropTypes.string, target: React.PropTypes.string, title: React.PropTypes.string, disabled: React.PropTypes.bool, previous: React.PropTypes.bool, next: React.PropTypes.bool, onSelect: React.PropTypes.func, eventKey: React.PropTypes.any }, getDefaultProps() { return { disabled: false, previous: false, next: false }; }, render() { let classes = { 'disabled': this.props.disabled, 'previous': this.props.previous, 'next': this.props.next }; return ( <li {...this.props} className={classNames(this.props.className, classes)}> <SafeAnchor href={this.props.href} title={this.props.title} target={this.props.target} onClick={this.handleSelect}> {this.props.children} </SafeAnchor> </li> ); }, handleSelect(e) { if (this.props.onSelect || this.props.disabled) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, this.props.href, this.props.target); } } } }); export default PageItem;
test/ButtonToolbarSpec.js
brynjagr/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import ButtonToolbar from '../src/ButtonToolbar'; import ButtonGroup from '../src/ButtonGroup'; import Button from '../src/Button'; describe('ButtonToolbar', function () { it('Should output a button toolbar', function () { let instance = ReactTestUtils.renderIntoDocument( <ButtonToolbar> <ButtonGroup> <Button> Title </Button> </ButtonGroup> </ButtonToolbar> ); let node = React.findDOMNode(instance); assert.equal(node.nodeName, 'DIV'); assert.ok(node.className.match(/\bbtn-toolbar\b/)); assert.equal(node.getAttribute('role'), 'toolbar'); }); });
src/components/shared/TicketEntry/index.js
Terrapin-Ticketing/althea
import React from 'react'; import moment from 'moment'; let TicketEntry = ({ticket, index}) => { console.log('ticket: ', ticket); if (ticket) { return ( <tr key={index}> <td> {moment(ticket.date).format('M/D/YY h:mm a')} </td> <td> {ticket.type} </td> <td> {ticket.barcode} </td> <td> {ticket.user.email} </td> <td> {ticket.user.firstName} </td> <td> {ticket.user.lastName} </td> </tr> ); } }; export default TicketEntry;
src/svg-icons/device/signal-cellular-connected-no-internet-3-bar.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularConnectedNoInternet3Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M17 22V7L2 22h15zm3-12v8h2v-8h-2zm0 12h2v-2h-2v2z"/> </SvgIcon> ); DeviceSignalCellularConnectedNoInternet3Bar = pure(DeviceSignalCellularConnectedNoInternet3Bar); DeviceSignalCellularConnectedNoInternet3Bar.displayName = 'DeviceSignalCellularConnectedNoInternet3Bar'; DeviceSignalCellularConnectedNoInternet3Bar.muiName = 'SvgIcon'; export default DeviceSignalCellularConnectedNoInternet3Bar;
ajax/libs/vue-material/0.5.0/vue-material.debug.js
redmunds/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["VueMaterial"] = factory(); else root["VueMaterial"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(253); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdAvatar = __webpack_require__(2); var _mdAvatar2 = _interopRequireDefault(_mdAvatar); var _mdAvatar3 = __webpack_require__(10); var _mdAvatar4 = _interopRequireDefault(_mdAvatar3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-avatar', Vue.extend(_mdAvatar2.default)); Vue.material.styles.push(_mdAvatar4.default); } module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(3) /* script */ __vue_exports__ = __webpack_require__(5) /* template */ var __vue_template__ = __webpack_require__(9) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdAvatar/mdAvatar.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-1cbfca0d", __vue_options__) } else { hotAPI.reload("data-v-1cbfca0d", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdAvatar.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 3 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 4 */ /***/ function(module, exports) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader module.exports = function() { var list = []; // return the list of modules as css string list.toString = function toString() { var result = []; for(var i = 0; i < this.length; i++) { var item = this[i]; if(item[2]) { result.push("@media " + item[2] + "{" + item[1] + "}"); } else { result.push(item[1]); } } return result.join(""); }; // import a list of modules into the list list.i = function(modules, mediaQuery) { if(typeof modules === "string") modules = [[null, modules, ""]]; var alreadyImportedModules = {}; for(var i = 0; i < this.length; i++) { var id = this[i][0]; if(typeof id === "number") alreadyImportedModules[id] = true; } for(i = 0; i < modules.length; i++) { var item = modules[i]; // skip already imported module // this implementation is not 100% perfect for weird media query combinations // when a module is imported multiple times with different media queries. // I hope this will never occur (Hey this way we have smaller bundles) if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) { if(mediaQuery && !item[2]) { item[2] = mediaQuery; } else if(mediaQuery) { item[2] = "(" + item[2] + ") and (" + mediaQuery + ")"; } list.push(item); } } }; return list; }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { mixins: [_mixin2.default] }; // // // // // // // // module.exports = exports['default']; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _vue = __webpack_require__(7); var _vue2 = _interopRequireDefault(_vue); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { props: { mdTheme: String }, data: function data() { return { closestThemedParent: false }; }, methods: { getClosestThemedParent: function getClosestThemedParent($parent) { if (!$parent || !$parent.$el || $parent._uid === 0) { return false; } if ($parent.mdTheme || $parent.mdName) { return $parent; } return this.getClosestThemedParent($parent.$parent); } }, computed: { themeClass: function themeClass() { if (this.mdTheme) { return 'md-theme-' + this.mdTheme; } var theme = this.closestThemedParent.mdTheme; if (!theme) { theme = this.closestThemedParent.mdName; } return 'md-theme-' + (theme || _vue2.default.material.currentTheme); } }, mounted: function mounted() { this.closestThemedParent = this.getClosestThemedParent(this.$parent); if (!_vue2.default.material.currentTheme) { _vue2.default.material.setCurrentTheme('default'); } } }; module.exports = exports['default']; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, global) {/*! * Vue.js v2.1.6 * (c) 2014-2016 Evan You * Released under the MIT License. */ 'use strict'; /* */ /** * Convert a value to a string that is actually rendered. */ function _toString (val) { return val == null ? '' : typeof val === 'object' ? JSON.stringify(val, null, 2) : String(val) } /** * Convert a input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber (val) { var n = parseFloat(val, 10); return (n || n === 0) ? n : val } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Remove an item from an array */ function remove$1 (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether the object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Check if value is primitive */ function isPrimitive (value) { return typeof value === 'string' || typeof value === 'number' } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) } } /** * Camelize a hyphen-delmited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { return str.charAt(0).toUpperCase() + str.slice(1) }); /** * Hyphenate a camelCase string. */ var hyphenateRE = /([^-])([A-Z])/g; var hyphenate = cached(function (str) { return str .replace(hyphenateRE, '$1-$2') .replace(hyphenateRE, '$1-$2') .toLowerCase() }); /** * Simple bind, faster than native */ function bind$1 (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } // record original fn length boundFn._length = fn.length; return boundFn } /** * Convert an Array-like object to a real Array. */ function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret } /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ var toString = Object.prototype.toString; var OBJECT_STRING = '[object Object]'; function isPlainObject (obj) { return toString.call(obj) === OBJECT_STRING } /** * Merge an Array of Objects into a single Object. */ function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res } /** * Perform no operation. */ function noop () {} /** * Always return false. */ var no = function () { return false; }; /** * Return same value */ var identity = function (_) { return _; }; /** * Generate a static keys string from compiler modules. */ function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual (a, b) { /* eslint-disable eqeqeq */ return a == b || ( isObject(a) && isObject(b) ? JSON.stringify(a) === JSON.stringify(b) : false ) /* eslint-enable eqeqeq */ } function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } return -1 } /* */ var config = { /** * Option merge strategies (used in core/util/options) */ optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Whether to enable devtools */ devtools: process.env.NODE_ENV !== 'production', /** * Error handler for watcher errors */ errorHandler: null, /** * Ignore certain custom elements */ ignoredElements: null, /** * Custom user key aliases for v-on */ keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * List of asset types that a component can own. */ _assetTypes: [ 'component', 'directive', 'filter' ], /** * List of lifecycle hooks. */ _lifecycleHooks: [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated' ], /** * Max circular updates allowed in a scheduler flush cycle. */ _maxUpdateCount: 100 }; /* */ /** * Check if a string starts with $ or _ */ function isReserved (str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F } /** * Define a property. */ function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Parse simple path. */ var bailRE = /[^\w.$]/; function parsePath (path) { if (bailRE.test(path)) { return } else { var segments = path.split('.'); return function (obj) { for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } } } /* */ /* globals MutationObserver */ // can we use __proto__? var hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = UA && UA.indexOf('android') > 0; var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA); // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative (Ctor) { return /native code/.test(Ctor.toString()) } /** * Defer a task to execute it asynchronously. */ var nextTick = (function () { var callbacks = []; var pending = false; var timerFunc; function nextTickHandler () { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; for (var i = 0; i < copies.length; i++) { copies[i](); } } // the nextTick behavior leverages the microtask queue, which can be accessed // via either native Promise.then or MutationObserver. // MutationObserver has wider support, however it is seriously bugged in // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It // completely stops working after triggering a few times... so, if native // Promise is available, we will use it: /* istanbul ignore if */ if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); var logError = function (err) { console.error(err); }; timerFunc = function () { p.then(nextTickHandler).catch(logError); // in problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; } else if (typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || // PhantomJS and iOS 7.x MutationObserver.toString() === '[object MutationObserverConstructor]' )) { // use MutationObserver where native Promise is not available, // e.g. PhantomJS IE11, iOS7, Android 4.4 var counter = 1; var observer = new MutationObserver(nextTickHandler); var textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = String(counter); }; } else { // fallback to setTimeout /* istanbul ignore next */ timerFunc = function () { setTimeout(nextTickHandler, 0); }; } return function queueNextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { cb.call(ctx); } if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; timerFunc(); } if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve) { _resolve = resolve; }) } } })(); var _Set; /* istanbul ignore if */ if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = (function () { function Set () { this.set = Object.create(null); } Set.prototype.has = function has (key) { return this.set[key] === true }; Set.prototype.add = function add (key) { this.set[key] = true; }; Set.prototype.clear = function clear () { this.set = Object.create(null); }; return Set; }()); } var warn = noop; var formatComponentName; if (process.env.NODE_ENV !== 'production') { var hasConsole = typeof console !== 'undefined'; warn = function (msg, vm) { if (hasConsole && (!config.silent)) { console.error("[Vue warn]: " + msg + " " + ( vm ? formatLocation(formatComponentName(vm)) : '' )); } }; formatComponentName = function (vm) { if (vm.$root === vm) { return 'root instance' } var name = vm._isVue ? vm.$options.name || vm.$options._componentTag : vm.name; return ( (name ? ("component <" + name + ">") : "anonymous component") + (vm._isVue && vm.$options.__file ? (" at " + (vm.$options.__file)) : '') ) }; var formatLocation = function (str) { if (str === 'anonymous component') { str += " - use the \"name\" option for better debugging messages."; } return ("\n(found in " + str + ")") }; } /* */ var uid$1 = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid$1++; this.subs = []; }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub (sub) { remove$1(this.subs, sub); }; Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify () { // stablize the subscriber list first var subs = this.subs.slice(); for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null; var targetStack = []; function pushTarget (_target) { if (Dep.target) { targetStack.push(Dep.target); } Dep.target = _target; } function popTarget () { Dep.target = targetStack.pop(); } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto);[ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] .forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator () { var arguments$1 = arguments; // avoid leaking arguments: // http://jsperf.com/closure-with-arguments var i = arguments.length; var args = new Array(i); while (i--) { args[i] = arguments$1[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 }); }); /* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * By default, when a reactive property is set, the new value is * also converted to become reactive. However when passing down props, * we don't want to force conversion because the value may be a nested value * under a frozen data structure. Converting it would defeat the optimization. */ var observerState = { shouldConvert: true, isSettingProps: false }; /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. */ var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { var augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { this.walk(value); } }; /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { defineReactive$$1(obj, keys[i], obj[keys[i]]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment an target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe (value) { if (!isObject(value)) { return } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( observerState.shouldConvert && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } return ob } /** * Define a reactive property on an Object. */ function defineReactive$$1 ( obj, key, val, customSetter ) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; var childOb = observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); } if (Array.isArray(value)) { dependArray(value); } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (process.env.NODE_ENV !== 'production' && customSetter) { customSetter(); } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = observe(newVal); dep.notify(); } }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set$1 (obj, key, val) { if (Array.isArray(obj)) { obj.length = Math.max(obj.length, key); obj.splice(key, 1, val); return val } if (hasOwn(obj, key)) { obj[key] = val; return } var ob = obj.__ob__; if (obj._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return } if (!ob) { obj[key] = val; return } defineReactive$$1(ob.value, key, val); ob.dep.notify(); return val } /** * Delete a property and trigger change if necessary. */ function del (obj, key) { var ob = obj.__ob__; if (obj._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid deleting properties on a Vue instance or its root $data ' + '- just set it to null.' ); return } if (!hasOwn(obj, key)) { return } delete obj[key]; if (!ob) { return } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; /** * Options with restrictions */ if (process.env.NODE_ENV !== 'production') { strats.el = strats.propsData = function (parent, child, vm, key) { if (!vm) { warn( "option \"" + key + "\" can only be used during instance " + 'creation with the `new` keyword.' ); } return defaultStrat(parent, child) }; } /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = Object.keys(from); for (var i = 0; i < keys.length; i++) { key = keys[i]; toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set$1(to, key, fromVal); } else if (isPlainObject(toVal) && isPlainObject(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') { process.env.NODE_ENV !== 'production' && warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm ); return parentVal } 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 } } } }; /** * Hooks and param attributes are merged as arrays. */ function mergeHook ( parentVal, childVal ) { return childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal } config._lifecycleHooks.forEach(function (hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets (parentVal, childVal) { var res = Object.create(parentVal || null); return childVal ? extend(res, childVal) : res } config._assetTypes.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function (parentVal, childVal) { /* istanbul ignore if */ 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 && !Array.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 (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; /** * Validate component names */ function checkComponents (options) { for (var key in options.components) { var lower = key.toLowerCase(); if (isBuiltInTag(lower) || config.isReservedTag(lower)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + key ); } } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps (options) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else if (process.env.NODE_ENV !== 'production') { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } options.props = res; } /** * Normalize raw function directives into object format. */ function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def = dirs[key]; if (typeof def === 'function') { dirs[key] = { bind: def, update: def }; } } } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions ( parent, child, vm ) { if (process.env.NODE_ENV !== 'production') { checkComponents(child); } normalizeProps(child); normalizeDirectives(child); var extendsFrom = child.extends; if (extendsFrom) { parent = typeof extendsFrom === 'function' ? mergeOptions(parent, extendsFrom.options, vm) : mergeOptions(parent, extendsFrom, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { var mixin = child.mixins[i]; if (mixin.prototype instanceof Vue$2) { mixin = mixin.options; } parent = mergeOptions(parent, mixin, vm); } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset ( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return } var assets = options[type]; // check local registration variations first if (hasOwn(assets, id)) { return assets[id] } var camelizedId = camelize(id); if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } var PascalCaseId = capitalize(camelizedId); if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } // fallback to prototype chain var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if (process.env.NODE_ENV !== 'production' && warnMissing && !res) { warn( 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, options ); } return res } /* */ function validateProp ( key, propOptions, propsData, vm ) { var prop = propOptions[key]; var absent = !hasOwn(propsData, key); var value = propsData[key]; // handle boolean props if (isBooleanType(prop.type)) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (value === '' || value === hyphenate(key)) { value = true; } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. var prevShouldConvert = observerState.shouldConvert; observerState.shouldConvert = true; observe(value); observerState.shouldConvert = prevShouldConvert; } if (process.env.NODE_ENV !== 'production') { assertProp(prop, key, value, vm, absent); } return value } /** * Get the default value of a prop. */ function getPropDefaultValue (vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined } var def = prop.default; // warn against non-factory defaults for Object & Array if (isObject(def)) { process.env.NODE_ENV !== 'production' && warn( 'Invalid default value for prop "' + key + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm ); } // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm[key] !== undefined) { return vm[key] } // call factory function for non-Function types return typeof def === 'function' && prop.type !== Function ? def.call(vm) : def } /** * Assert whether a prop is valid. */ function assertProp ( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return } if (value == null && !prop.required) { return } var type = prop.type; var valid = !type || type === true; var expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType); valid = assertedType.valid; } } if (!valid) { warn( 'Invalid prop: type check failed for prop "' + name + '".' + ' Expected ' + expectedTypes.map(capitalize).join(', ') + ', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.', vm ); return } var validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } /** * Assert the type of a value */ function assertType (value, type) { var valid; var expectedType = getType(type); if (expectedType === 'String') { valid = typeof value === (expectedType = 'string'); } else if (expectedType === 'Number') { valid = typeof value === (expectedType = 'number'); } else if (expectedType === 'Boolean') { valid = typeof value === (expectedType = 'boolean'); } else if (expectedType === 'Function') { valid = typeof value === (expectedType = 'function'); } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType (fn) { var match = fn && fn.toString().match(/^\s*function (\w+)/); return match && match[1] } function isBooleanType (fn) { if (!Array.isArray(fn)) { return getType(fn) === 'Boolean' } for (var i = 0, len = fn.length; i < len; i++) { if (getType(fn[i]) === 'Boolean') { return true } } /* istanbul ignore next */ return false } var util = Object.freeze({ defineReactive: defineReactive$$1, _toString: _toString, toNumber: toNumber, makeMap: makeMap, isBuiltInTag: isBuiltInTag, remove: remove$1, hasOwn: hasOwn, isPrimitive: isPrimitive, cached: cached, camelize: camelize, capitalize: capitalize, hyphenate: hyphenate, bind: bind$1, toArray: toArray, extend: extend, isObject: isObject, isPlainObject: isPlainObject, toObject: toObject, noop: noop, no: no, identity: identity, genStaticKeys: genStaticKeys, looseEqual: looseEqual, looseIndexOf: looseIndexOf, isReserved: isReserved, def: def, parsePath: parsePath, hasProto: hasProto, inBrowser: inBrowser, UA: UA, isIE: isIE, isIE9: isIE9, isEdge: isEdge, isAndroid: isAndroid, isIOS: isIOS, isServerRendering: isServerRendering, devtools: devtools, nextTick: nextTick, get _Set () { return _Set; }, mergeOptions: mergeOptions, resolveAsset: resolveAsset, get warn () { return warn; }, get formatComponentName () { return formatComponentName; }, validateProp: validateProp }); /* not type checking this file because flow doesn't play well with Proxy */ var initProxy; if (process.env.NODE_ENV !== 'production') { var allowedGlobals = makeMap( 'Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + 'require' // for Webpack/Browserify ); var warnNonPresent = function (target, key) { warn( "Property or method \"" + key + "\" is not defined on the instance but " + "referenced during render. Make sure to declare reactive data " + "properties in the data option.", target ); }; var hasProxy = typeof Proxy !== 'undefined' && Proxy.toString().match(/native code/); if (hasProxy) { var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta'); config.keyCodes = new Proxy(config.keyCodes, { set: function set (target, key, value) { if (isBuiltInModifier(key)) { warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); return false } else { target[key] = value; return true } } }); } var hasHandler = { has: function has (target, key) { var has = key in target; var isAllowed = allowedGlobals(key) || key.charAt(0) === '_'; if (!has && !isAllowed) { warnNonPresent(target, key); } return has || !isAllowed } }; var getHandler = { get: function get (target, key) { if (typeof key === 'string' && !(key in target)) { warnNonPresent(target, key); } return target[key] } }; initProxy = function initProxy (vm) { if (hasProxy) { // determine which proxy handler to use var options = vm.$options; var handlers = options.render && options.render._withStripped ? getHandler : hasHandler; vm._renderProxy = new Proxy(vm, handlers); } else { vm._renderProxy = vm; } }; } /* */ var queue = []; var has$1 = {}; var circular = {}; var waiting = false; var flushing = false; var index = 0; /** * Reset the scheduler's state. */ function resetSchedulerState () { queue.length = 0; has$1 = {}; if (process.env.NODE_ENV !== 'production') { circular = {}; } waiting = flushing = false; } /** * Flush both queues and run the watchers. */ function flushSchedulerQueue () { flushing = true; // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort(function (a, b) { return a.id - b.id; }); // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { var watcher = queue[index]; var id = watcher.id; has$1[id] = null; watcher.run(); // in dev build, check and stop circular updates. if (process.env.NODE_ENV !== 'production' && has$1[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > config._maxUpdateCount) { warn( 'You may have an infinite update loop ' + ( watcher.user ? ("in watcher with expression \"" + (watcher.expression) + "\"") : "in a component render function." ), watcher.vm ); break } } } // devtool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } resetSchedulerState(); } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. */ function queueWatcher (watcher) { var id = watcher.id; if (has$1[id] == null) { has$1[id] = true; if (!flushing) { queue.push(watcher); } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. var i = queue.length - 1; while (i >= 0 && queue[i].id > watcher.id) { i--; } queue.splice(Math.max(i, index) + 1, 0, watcher); } // queue the flush if (!waiting) { waiting = true; nextTick(flushSchedulerQueue); } } } /* */ var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */ var Watcher = function Watcher ( vm, expOrFn, cb, options ) { if ( options === void 0 ) options = {}; this.vm = vm; vm._watchers.push(this); // options this.deep = !!options.deep; this.user = !!options.user; this.lazy = !!options.lazy; this.sync = !!options.sync; this.expression = expOrFn.toString(); this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = parsePath(expOrFn); if (!this.getter) { this.getter = function () {}; process.env.NODE_ENV !== 'production' && warn( "Failed watching path: \"" + expOrFn + "\" " + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ); } } this.value = this.lazy ? undefined : this.get(); }; /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function get () { pushTarget(this); var value = this.getter.call(this.vm, this.vm); // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); return value }; /** * Add a dependency to this directive. */ Watcher.prototype.addDep = function addDep (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function cleanupDeps () { var this$1 = this; var i = this.deps.length; while (i--) { var dep = this$1.deps[i]; if (!this$1.newDepIds.has(dep.id)) { dep.removeSub(this$1); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. */ Watcher.prototype.update = function update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; /** * Scheduler job interface. * Will be called by the scheduler. */ Watcher.prototype.run = function run () { if (this.active) { var value = this.get(); if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value var oldValue = this.value; this.value = value; if (this.user) { try { this.cb.call(this.vm, value, oldValue); } catch (e) { /* istanbul ignore else */ if (config.errorHandler) { config.errorHandler.call(null, e, this.vm); } else { process.env.NODE_ENV !== 'production' && warn( ("Error in watcher \"" + (this.expression) + "\""), this.vm ); throw e } } } else { this.cb.call(this.vm, value, oldValue); } } } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function evaluate () { this.value = this.get(); this.dirty = false; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function depend () { var this$1 = this; var i = this.deps.length; while (i--) { this$1.deps[i].depend(); } }; /** * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function teardown () { var this$1 = this; if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed or is performing a v-for // re-render (the watcher list is then filtered by v-for). if (!this.vm._isBeingDestroyed && !this.vm._vForRemoving) { remove$1(this.vm._watchers, this); } var i = this.deps.length; while (i--) { this$1.deps[i].removeSub(this$1); } this.active = false; } }; /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ var seenObjects = new _Set(); function traverse (val) { seenObjects.clear(); _traverse(val, seenObjects); } function _traverse (val, seen) { var i, keys; var isA = Array.isArray(val); if ((!isA && !isObject(val)) || !Object.isExtensible(val)) { return } if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } /* */ function initState (vm) { vm._watchers = []; initProps(vm); initMethods(vm); initData(vm); initComputed(vm); initWatch(vm); } var isReservedProp = { key: 1, ref: 1, slot: 1 }; function initProps (vm) { var props = vm.$options.props; if (props) { var propsData = vm.$options.propsData || {}; var keys = vm.$options._propKeys = Object.keys(props); var isRoot = !vm.$parent; // root instance props should be converted observerState.shouldConvert = isRoot; var loop = function ( i ) { var key = keys[i]; /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { if (isReservedProp[key]) { warn( ("\"" + key + "\" is a reserved attribute and cannot be used as component prop."), vm ); } defineReactive$$1(vm, key, validateProp(key, props, propsData, vm), function () { if (vm.$parent && !observerState.isSettingProps) { warn( "Avoid mutating a prop directly since the value will be " + "overwritten whenever the parent component re-renders. " + "Instead, use a data or computed property based on the prop's " + "value. Prop being mutated: \"" + key + "\"", vm ); } }); } else { defineReactive$$1(vm, key, validateProp(key, props, propsData, vm)); } }; for (var i = 0; i < keys.length; i++) loop( i ); observerState.shouldConvert = true; } } function initData (vm) { var data = vm.$options.data; data = vm._data = typeof data === 'function' ? data.call(vm) : data || {}; if (!isPlainObject(data)) { data = {}; process.env.NODE_ENV !== 'production' && warn( 'data functions should return an object:\n' + 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function', vm ); } // proxy data on instance var keys = Object.keys(data); var props = vm.$options.props; var i = keys.length; while (i--) { if (props && hasOwn(props, keys[i])) { process.env.NODE_ENV !== 'production' && warn( "The data property \"" + (keys[i]) + "\" is already declared as a prop. " + "Use prop default value instead.", vm ); } else { proxy(vm, keys[i]); } } // observe data observe(data); data.__ob__ && data.__ob__.vmCount++; } var computedSharedDefinition = { enumerable: true, configurable: true, get: noop, set: noop }; function initComputed (vm) { var computed = vm.$options.computed; if (computed) { for (var key in computed) { var userDef = computed[key]; if (typeof userDef === 'function') { computedSharedDefinition.get = makeComputedGetter(userDef, vm); computedSharedDefinition.set = noop; } else { computedSharedDefinition.get = userDef.get ? userDef.cache !== false ? makeComputedGetter(userDef.get, vm) : bind$1(userDef.get, vm) : noop; computedSharedDefinition.set = userDef.set ? bind$1(userDef.set, vm) : noop; } Object.defineProperty(vm, key, computedSharedDefinition); } } } function makeComputedGetter (getter, owner) { var watcher = new Watcher(owner, getter, noop, { lazy: true }); return function computedGetter () { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value } } function initMethods (vm) { var methods = vm.$options.methods; if (methods) { for (var key in methods) { vm[key] = methods[key] == null ? noop : bind$1(methods[key], vm); if (process.env.NODE_ENV !== 'production' && methods[key] == null) { warn( "method \"" + key + "\" has an undefined value in the component definition. " + "Did you reference the function correctly?", vm ); } } } } function initWatch (vm) { var watch = vm.$options.watch; if (watch) { for (var key in watch) { var handler = watch[key]; if (Array.isArray(handler)) { for (var i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]); } } else { createWatcher(vm, key, handler); } } } } function createWatcher (vm, key, handler) { var options; if (isPlainObject(handler)) { options = handler; handler = handler.handler; } if (typeof handler === 'string') { handler = vm[handler]; } vm.$watch(key, handler, options); } function stateMixin (Vue) { // flow somehow has problems with directly declared definition object // when using Object.defineProperty, so we have to procedurally build up // the object here. var dataDef = {}; dataDef.get = function () { return this._data }; if (process.env.NODE_ENV !== 'production') { dataDef.set = function (newData) { warn( 'Avoid replacing instance root $data. ' + 'Use nested data properties instead.', this ); }; } Object.defineProperty(Vue.prototype, '$data', dataDef); Vue.prototype.$set = set$1; Vue.prototype.$delete = del; Vue.prototype.$watch = function ( expOrFn, cb, options ) { var vm = this; options = options || {}; options.user = true; var watcher = new Watcher(vm, expOrFn, cb, options); if (options.immediate) { cb.call(vm, watcher.value); } return function unwatchFn () { watcher.teardown(); } }; } function proxy (vm, key) { if (!isReserved(key)) { Object.defineProperty(vm, key, { configurable: true, enumerable: true, get: function proxyGetter () { return vm._data[key] }, set: function proxySetter (val) { vm._data[key] = val; } }); } } /* */ var VNode = function VNode ( tag, data, children, text, elm, context, componentOptions ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.functionalContext = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.child = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; }; var createEmptyVNode = function () { var node = new VNode(); node.text = ''; node.isComment = true; return node }; function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode (vnode) { var cloned = new VNode( vnode.tag, vnode.data, vnode.children, vnode.text, vnode.elm, vnode.context, vnode.componentOptions ); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isCloned = true; return cloned } function cloneVNodes (vnodes) { var res = new Array(vnodes.length); for (var i = 0; i < vnodes.length; i++) { res[i] = cloneVNode(vnodes[i]); } return res } /* */ var activeInstance = null; function initLifecycle (vm) { var options = vm.$options; // locate first non-abstract parent var parent = options.parent; if (parent && !options.abstract) { while (parent.$options.abstract && parent.$parent) { parent = parent.$parent; } parent.$children.push(vm); } vm.$parent = parent; vm.$root = parent ? parent.$root : vm; vm.$children = []; vm.$refs = {}; vm._watcher = null; vm._inactive = false; vm._isMounted = false; vm._isDestroyed = false; vm._isBeingDestroyed = false; } function lifecycleMixin (Vue) { Vue.prototype._mount = function ( el, hydrating ) { var vm = this; vm.$el = el; if (!vm.$options.render) { vm.$options.render = createEmptyVNode; if (process.env.NODE_ENV !== 'production') { /* istanbul ignore if */ if (vm.$options.template && vm.$options.template.charAt(0) !== '#') { warn( 'You are using the runtime-only build of Vue where the template ' + 'option is not available. Either pre-compile the templates into ' + 'render functions, or use the compiler-included build.', vm ); } else { warn( 'Failed to mount component: template or render function not defined.', vm ); } } } callHook(vm, 'beforeMount'); vm._watcher = new Watcher(vm, function () { vm._update(vm._render(), hydrating); }, noop); hydrating = false; // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true; callHook(vm, 'mounted'); } return vm }; Vue.prototype._update = function (vnode, hydrating) { var vm = this; if (vm._isMounted) { callHook(vm, 'beforeUpdate'); } var prevEl = vm.$el; var prevVnode = vm._vnode; var prevActiveInstance = activeInstance; activeInstance = vm; vm._vnode = vnode; // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // initial render vm.$el = vm.__patch__( vm.$el, vnode, hydrating, false /* removeOnly */, vm.$options._parentElm, vm.$options._refElm ); } else { // updates vm.$el = vm.__patch__(prevVnode, vnode); } activeInstance = prevActiveInstance; // update __vue__ reference if (prevEl) { prevEl.__vue__ = null; } if (vm.$el) { vm.$el.__vue__ = vm; } // if parent is an HOC, update its $el as well if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) { vm.$parent.$el = vm.$el; } if (vm._isMounted) { callHook(vm, 'updated'); } }; Vue.prototype._updateFromParent = function ( propsData, listeners, parentVnode, renderChildren ) { var vm = this; var hasChildren = !!(vm.$options._renderChildren || renderChildren); vm.$options._parentVnode = parentVnode; vm.$vnode = parentVnode; // update vm's placeholder node without re-render if (vm._vnode) { // update child tree's parent vm._vnode.parent = parentVnode; } vm.$options._renderChildren = renderChildren; // update props if (propsData && vm.$options.props) { observerState.shouldConvert = false; if (process.env.NODE_ENV !== 'production') { observerState.isSettingProps = true; } var propKeys = vm.$options._propKeys || []; for (var i = 0; i < propKeys.length; i++) { var key = propKeys[i]; vm[key] = validateProp(key, vm.$options.props, propsData, vm); } observerState.shouldConvert = true; if (process.env.NODE_ENV !== 'production') { observerState.isSettingProps = false; } vm.$options.propsData = propsData; } // update listeners if (listeners) { var oldListeners = vm.$options._parentListeners; vm.$options._parentListeners = listeners; vm._updateListeners(listeners, oldListeners); } // resolve slots + force update if has children if (hasChildren) { vm.$slots = resolveSlots(renderChildren, parentVnode.context); vm.$forceUpdate(); } }; Vue.prototype.$forceUpdate = function () { var vm = this; if (vm._watcher) { vm._watcher.update(); } }; Vue.prototype.$destroy = function () { var vm = this; if (vm._isBeingDestroyed) { return } callHook(vm, 'beforeDestroy'); vm._isBeingDestroyed = true; // remove self from parent var parent = vm.$parent; if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { remove$1(parent.$children, vm); } // teardown watchers if (vm._watcher) { vm._watcher.teardown(); } var i = vm._watchers.length; while (i--) { vm._watchers[i].teardown(); } // remove reference from data ob // frozen object may not have observer. if (vm._data.__ob__) { vm._data.__ob__.vmCount--; } // call the last hook... vm._isDestroyed = true; callHook(vm, 'destroyed'); // turn off all instance listeners. vm.$off(); // remove __vue__ reference if (vm.$el) { vm.$el.__vue__ = null; } // invoke destroy hooks on current rendered tree vm.__patch__(vm._vnode, null); }; } function callHook (vm, hook) { var handlers = vm.$options[hook]; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { handlers[i].call(vm); } } vm.$emit('hook:' + hook); } /* */ var hooks = { init: init, prepatch: prepatch, insert: insert, destroy: destroy$1 }; var hooksToMerge = Object.keys(hooks); function createComponent ( Ctor, data, context, children, tag ) { if (!Ctor) { return } var baseCtor = context.$options._base; if (isObject(Ctor)) { Ctor = baseCtor.extend(Ctor); } if (typeof Ctor !== 'function') { if (process.env.NODE_ENV !== 'production') { warn(("Invalid Component definition: " + (String(Ctor))), context); } return } // async component if (!Ctor.cid) { if (Ctor.resolved) { Ctor = Ctor.resolved; } else { Ctor = resolveAsyncComponent(Ctor, baseCtor, function () { // it's ok to queue this on every render because // $forceUpdate is buffered by the scheduler. context.$forceUpdate(); }); if (!Ctor) { // return nothing if this is indeed an async component // wait for the callback to trigger parent update. return } } } // resolve constructor options in case global mixins are applied after // component constructor creation resolveConstructorOptions(Ctor); data = data || {}; // extract props var propsData = extractProps(data, Ctor); // functional component if (Ctor.options.functional) { return createFunctionalComponent(Ctor, propsData, data, context, children) } // extract listeners, since these needs to be treated as // child component listeners instead of DOM listeners var listeners = data.on; // replace with listeners with .native modifier data.on = data.nativeOn; if (Ctor.options.abstract) { // abstract components do not keep anything // other than props & listeners data = {}; } // merge component management hooks onto the placeholder node mergeHooks(data); // return a placeholder vnode var name = Ctor.options.name || tag; var vnode = new VNode( ("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')), data, undefined, undefined, undefined, context, { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children } ); return vnode } function createFunctionalComponent ( Ctor, propsData, data, context, children ) { var props = {}; var propOptions = Ctor.options.props; if (propOptions) { for (var key in propOptions) { props[key] = validateProp(key, propOptions, propsData); } } // ensure the createElement function in functional components // gets a unique context - this is necessary for correct named slot check var _context = Object.create(context); var h = function (a, b, c, d) { return createElement(_context, a, b, c, d, true); }; var vnode = Ctor.options.render.call(null, h, { props: props, data: data, parent: context, children: children, slots: function () { return resolveSlots(children, context); } }); if (vnode instanceof VNode) { vnode.functionalContext = context; if (data.slot) { (vnode.data || (vnode.data = {})).slot = data.slot; } } return vnode } function createComponentInstanceForVnode ( vnode, // we know it's MountedComponentVNode but flow doesn't parent, // activeInstance in lifecycle state parentElm, refElm ) { var vnodeComponentOptions = vnode.componentOptions; var options = { _isComponent: true, parent: parent, propsData: vnodeComponentOptions.propsData, _componentTag: vnodeComponentOptions.tag, _parentVnode: vnode, _parentListeners: vnodeComponentOptions.listeners, _renderChildren: vnodeComponentOptions.children, _parentElm: parentElm || null, _refElm: refElm || null }; // check inline-template render functions var inlineTemplate = vnode.data.inlineTemplate; if (inlineTemplate) { options.render = inlineTemplate.render; options.staticRenderFns = inlineTemplate.staticRenderFns; } return new vnodeComponentOptions.Ctor(options) } function init ( vnode, hydrating, parentElm, refElm ) { if (!vnode.child || vnode.child._isDestroyed) { var child = vnode.child = createComponentInstanceForVnode( vnode, activeInstance, parentElm, refElm ); child.$mount(hydrating ? vnode.elm : undefined, hydrating); } else if (vnode.data.keepAlive) { // kept-alive components, treat as a patch var mountedNode = vnode; // work around flow prepatch(mountedNode, mountedNode); } } function prepatch ( oldVnode, vnode ) { var options = vnode.componentOptions; var child = vnode.child = oldVnode.child; child._updateFromParent( options.propsData, // updated props options.listeners, // updated listeners vnode, // new parent vnode options.children // new children ); } function insert (vnode) { if (!vnode.child._isMounted) { vnode.child._isMounted = true; callHook(vnode.child, 'mounted'); } if (vnode.data.keepAlive) { vnode.child._inactive = false; callHook(vnode.child, 'activated'); } } function destroy$1 (vnode) { if (!vnode.child._isDestroyed) { if (!vnode.data.keepAlive) { vnode.child.$destroy(); } else { vnode.child._inactive = true; callHook(vnode.child, 'deactivated'); } } } function resolveAsyncComponent ( factory, baseCtor, cb ) { if (factory.requested) { // pool callbacks factory.pendingCallbacks.push(cb); } else { factory.requested = true; var cbs = factory.pendingCallbacks = [cb]; var sync = true; var resolve = function (res) { if (isObject(res)) { res = baseCtor.extend(res); } // cache resolved factory.resolved = res; // invoke callbacks only if this is not a synchronous resolve // (async resolves are shimmed as synchronous during SSR) if (!sync) { for (var i = 0, l = cbs.length; i < l; i++) { cbs[i](res); } } }; var reject = function (reason) { process.env.NODE_ENV !== 'production' && warn( "Failed to resolve async component: " + (String(factory)) + (reason ? ("\nReason: " + reason) : '') ); }; var res = factory(resolve, reject); // handle promise if (res && typeof res.then === 'function' && !factory.resolved) { res.then(resolve, reject); } sync = false; // return in case resolved synchronously return factory.resolved } } function extractProps (data, Ctor) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. var propOptions = Ctor.options.props; if (!propOptions) { return } var res = {}; var attrs = data.attrs; var props = data.props; var domProps = data.domProps; if (attrs || props || domProps) { for (var key in propOptions) { var altKey = hyphenate(key); checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey) || checkProp(res, domProps, key, altKey); } } return res } function checkProp ( res, hash, key, altKey, preserve ) { if (hash) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true } } return false } function mergeHooks (data) { if (!data.hook) { data.hook = {}; } for (var i = 0; i < hooksToMerge.length; i++) { var key = hooksToMerge[i]; var fromParent = data.hook[key]; var ours = hooks[key]; data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours; } } function mergeHook$1 (one, two) { return function (a, b, c, d) { one(a, b, c, d); two(a, b, c, d); } } /* */ function mergeVNodeHook (def, hookKey, hook, key) { key = key + hookKey; var injectedHash = def.__injected || (def.__injected = {}); if (!injectedHash[key]) { injectedHash[key] = true; var oldHook = def[hookKey]; if (oldHook) { def[hookKey] = function () { oldHook.apply(this, arguments); hook.apply(this, arguments); }; } else { def[hookKey] = hook; } } } /* */ function updateListeners ( on, oldOn, add, remove$$1, vm ) { var name, cur, old, fn, event, capture, once; for (name in on) { cur = on[name]; old = oldOn[name]; if (!cur) { process.env.NODE_ENV !== 'production' && warn( "Invalid handler for event \"" + name + "\": got " + String(cur), vm ); } else if (!old) { once = name.charAt(0) === '~'; // Prefixed last, checked first event = once ? name.slice(1) : name; capture = event.charAt(0) === '!'; event = capture ? event.slice(1) : event; if (Array.isArray(cur)) { add(event, (cur.invoker = arrInvoker(cur)), once, capture); } else { if (!cur.invoker) { fn = cur; cur = on[name] = {}; cur.fn = fn; cur.invoker = fnInvoker(cur); } add(event, cur.invoker, once, capture); } } else if (cur !== old) { if (Array.isArray(old)) { old.length = cur.length; for (var i = 0; i < old.length; i++) { old[i] = cur[i]; } on[name] = old; } else { old.fn = cur; on[name] = old; } } } for (name in oldOn) { if (!on[name]) { once = name.charAt(0) === '~'; // Prefixed last, checked first event = once ? name.slice(1) : name; capture = event.charAt(0) === '!'; event = capture ? event.slice(1) : event; remove$$1(event, oldOn[name].invoker, capture); } } } function arrInvoker (arr) { return function (ev) { var arguments$1 = arguments; var single = arguments.length === 1; for (var i = 0; i < arr.length; i++) { single ? arr[i](ev) : arr[i].apply(null, arguments$1); } } } function fnInvoker (o) { return function (ev) { var single = arguments.length === 1; single ? o.fn(ev) : o.fn.apply(null, arguments); } } /* */ function normalizeChildren (children) { return isPrimitive(children) ? [createTextVNode(children)] : Array.isArray(children) ? normalizeArrayChildren(children) : undefined } function normalizeArrayChildren (children, nestedIndex) { var res = []; var i, c, last; for (i = 0; i < children.length; i++) { c = children[i]; if (c == null || typeof c === 'boolean') { continue } last = res[res.length - 1]; // nested if (Array.isArray(c)) { res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i))); } else if (isPrimitive(c)) { if (last && last.text) { last.text += String(c); } else if (c !== '') { // convert primitive to vnode res.push(createTextVNode(c)); } } else { if (c.text && last && last.text) { res[res.length - 1] = createTextVNode(last.text + c.text); } else { // default key for nested array children (likely generated by v-for) if (c.tag && c.key == null && nestedIndex != null) { c.key = "__vlist" + nestedIndex + "_" + i + "__"; } res.push(c); } } } return res } /* */ function getFirstComponentChild (children) { return children && children.filter(function (c) { return c && c.componentOptions; })[0] } /* */ // wrapper function for providing a more flexible interface // without getting yelled at by flow function createElement ( context, tag, data, children, needNormalization, alwaysNormalize ) { if (Array.isArray(data) || isPrimitive(data)) { needNormalization = children; children = data; data = undefined; } if (alwaysNormalize) { needNormalization = true; } return _createElement(context, tag, data, children, needNormalization) } function _createElement ( context, tag, data, children, needNormalization ) { if (data && data.__ob__) { process.env.NODE_ENV !== 'production' && warn( "Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" + 'Always create fresh vnode data objects in each render!', context ); return createEmptyVNode() } if (!tag) { // in case of component :is set to falsy value return createEmptyVNode() } // support single function children as default scoped slot if (Array.isArray(children) && typeof children[0] === 'function') { data = data || {}; data.scopedSlots = { default: children[0] }; children.length = 0; } if (needNormalization) { children = normalizeChildren(children); } var vnode, ns; if (typeof tag === 'string') { var Ctor; ns = config.getTagNamespace(tag); if (config.isReservedTag(tag)) { // platform built-in elements vnode = new VNode( config.parsePlatformTagName(tag), data, children, undefined, undefined, context ); } else if ((Ctor = resolveAsset(context.$options, 'components', tag))) { // component vnode = createComponent(Ctor, data, context, children, tag); } else { // unknown or unlisted namespaced elements // check at runtime because it may get assigned a namespace when its // parent normalizes children ns = tag === 'foreignObject' ? 'xhtml' : ns; vnode = new VNode( tag, data, children, undefined, undefined, context ); } } else { // direct component options / constructor vnode = createComponent(tag, data, context, children); } if (vnode) { if (ns) { applyNS(vnode, ns); } return vnode } else { return createEmptyVNode() } } function applyNS (vnode, ns) { vnode.ns = ns; if (vnode.children) { for (var i = 0, l = vnode.children.length; i < l; i++) { var child = vnode.children[i]; if (child.tag && !child.ns) { applyNS(child, ns); } } } } /* */ function initRender (vm) { vm.$vnode = null; // the placeholder node in parent tree vm._vnode = null; // the root of the child tree vm._staticTrees = null; var parentVnode = vm.$options._parentVnode; var renderContext = parentVnode && parentVnode.context; vm.$slots = resolveSlots(vm.$options._renderChildren, renderContext); vm.$scopedSlots = {}; // bind the createElement fn to this instance // so that we get proper render context inside it. // args order: tag, data, children, needNormalization, alwaysNormalize // internal version is used by render functions compiled from templates vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); }; // normalization is always applied for the public version, used in // user-written render functions. vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); }; if (vm.$options.el) { vm.$mount(vm.$options.el); } } function renderMixin (Vue) { Vue.prototype.$nextTick = function (fn) { return nextTick(fn, this) }; Vue.prototype._render = function () { var vm = this; var ref = vm.$options; var render = ref.render; var staticRenderFns = ref.staticRenderFns; var _parentVnode = ref._parentVnode; if (vm._isMounted) { // clone slot nodes on re-renders for (var key in vm.$slots) { vm.$slots[key] = cloneVNodes(vm.$slots[key]); } } if (_parentVnode && _parentVnode.data.scopedSlots) { vm.$scopedSlots = _parentVnode.data.scopedSlots; } if (staticRenderFns && !vm._staticTrees) { vm._staticTrees = []; } // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode; // render self var vnode; try { vnode = render.call(vm._renderProxy, vm.$createElement); } catch (e) { /* istanbul ignore else */ if (config.errorHandler) { config.errorHandler.call(null, e, vm); } else { if (process.env.NODE_ENV !== 'production') { warn(("Error when rendering " + (formatComponentName(vm)) + ":")); } throw e } // return previous vnode to prevent render error causing blank component vnode = vm._vnode; } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ); } vnode = createEmptyVNode(); } // set parent vnode.parent = _parentVnode; return vnode }; // toString for mustaches Vue.prototype._s = _toString; // convert text to vnode Vue.prototype._v = createTextVNode; // number conversion Vue.prototype._n = toNumber; // empty vnode Vue.prototype._e = createEmptyVNode; // loose equal Vue.prototype._q = looseEqual; // loose indexOf Vue.prototype._i = looseIndexOf; // render static tree by index Vue.prototype._m = function renderStatic ( index, isInFor ) { var tree = this._staticTrees[index]; // if has already-rendered static tree and not inside v-for, // we can reuse the same tree by doing a shallow clone. if (tree && !isInFor) { return Array.isArray(tree) ? cloneVNodes(tree) : cloneVNode(tree) } // otherwise, render a fresh tree. tree = this._staticTrees[index] = this.$options.staticRenderFns[index].call(this._renderProxy); markStatic(tree, ("__static__" + index), false); return tree }; // mark node as static (v-once) Vue.prototype._o = function markOnce ( tree, index, key ) { markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true); return tree }; function markStatic (tree, key, isOnce) { if (Array.isArray(tree)) { for (var i = 0; i < tree.length; i++) { if (tree[i] && typeof tree[i] !== 'string') { markStaticNode(tree[i], (key + "_" + i), isOnce); } } } else { markStaticNode(tree, key, isOnce); } } function markStaticNode (node, key, isOnce) { node.isStatic = true; node.key = key; node.isOnce = isOnce; } // filter resolution helper Vue.prototype._f = function resolveFilter (id) { return resolveAsset(this.$options, 'filters', id, true) || identity }; // render v-for Vue.prototype._l = function renderList ( val, render ) { var ret, i, l, keys, key; if (Array.isArray(val)) { ret = new Array(val.length); for (i = 0, l = val.length; i < l; i++) { ret[i] = render(val[i], i); } } else if (typeof val === 'number') { ret = new Array(val); for (i = 0; i < val; i++) { ret[i] = render(i + 1, i); } } else if (isObject(val)) { keys = Object.keys(val); ret = new Array(keys.length); for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; ret[i] = render(val[key], key, i); } } return ret }; // renderSlot Vue.prototype._t = function ( name, fallback, props ) { var scopedSlotFn = this.$scopedSlots[name]; if (scopedSlotFn) { // scoped slot return scopedSlotFn(props || {}) || fallback } else { var slotNodes = this.$slots[name]; // warn duplicate slot usage if (slotNodes && process.env.NODE_ENV !== 'production') { slotNodes._rendered && warn( "Duplicate presence of slot \"" + name + "\" found in the same render tree " + "- this will likely cause render errors.", this ); slotNodes._rendered = true; } return slotNodes || fallback } }; // apply v-bind object Vue.prototype._b = function bindProps ( data, tag, value, asProp ) { if (value) { if (!isObject(value)) { process.env.NODE_ENV !== 'production' && warn( 'v-bind without argument expects an Object or Array value', this ); } else { if (Array.isArray(value)) { value = toObject(value); } for (var key in value) { if (key === 'class' || key === 'style') { data[key] = value[key]; } else { var hash = asProp || config.mustUseProp(tag, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {}); hash[key] = value[key]; } } } } return data }; // check v-on keyCodes Vue.prototype._k = function checkKeyCodes ( eventKeyCode, key, builtInAlias ) { var keyCodes = config.keyCodes[key] || builtInAlias; if (Array.isArray(keyCodes)) { return keyCodes.indexOf(eventKeyCode) === -1 } else { return keyCodes !== eventKeyCode } }; } function resolveSlots ( children, context ) { var slots = {}; if (!children) { return slots } var defaultSlot = []; var name, child; for (var i = 0, l = children.length; i < l; i++) { child = children[i]; // named slots should only be respected if the vnode was rendered in the // same context. if ((child.context === context || child.functionalContext === context) && child.data && (name = child.data.slot)) { var slot = (slots[name] || (slots[name] = [])); if (child.tag === 'template') { slot.push.apply(slot, child.children); } else { slot.push(child); } } else { defaultSlot.push(child); } } // ignore single whitespace if (defaultSlot.length && !( defaultSlot.length === 1 && (defaultSlot[0].text === ' ' || defaultSlot[0].isComment) )) { slots.default = defaultSlot; } return slots } /* */ function initEvents (vm) { vm._events = Object.create(null); // init parent attached events var listeners = vm.$options._parentListeners; var add = function (event, fn, once) { once ? vm.$once(event, fn) : vm.$on(event, fn); }; var remove$$1 = bind$1(vm.$off, vm); vm._updateListeners = function (listeners, oldListeners) { updateListeners(listeners, oldListeners || {}, add, remove$$1, vm); }; if (listeners) { vm._updateListeners(listeners); } } function eventsMixin (Vue) { Vue.prototype.$on = function (event, fn) { var vm = this;(vm._events[event] || (vm._events[event] = [])).push(fn); return vm }; Vue.prototype.$once = function (event, fn) { var vm = this; function on () { vm.$off(event, on); fn.apply(vm, arguments); } on.fn = fn; vm.$on(event, on); return vm }; Vue.prototype.$off = function (event, fn) { var vm = this; // all if (!arguments.length) { vm._events = Object.create(null); return vm } // specific event var cbs = vm._events[event]; if (!cbs) { return vm } if (arguments.length === 1) { vm._events[event] = null; return vm } // specific handler var cb; var i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { cbs.splice(i, 1); break } } return vm }; Vue.prototype.$emit = function (event) { var vm = this; var cbs = vm._events[event]; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; var args = toArray(arguments, 1); for (var i = 0, l = cbs.length; i < l; i++) { cbs[i].apply(vm, args); } } return vm }; } /* */ var uid = 0; function initMixin (Vue) { Vue.prototype._init = function (options) { var vm = this; // a uid vm._uid = uid++; // a flag to avoid this being observed vm._isVue = true; // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options); } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ); } /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { initProxy(vm); } else { vm._renderProxy = vm; } // expose real self vm._self = vm; initLifecycle(vm); initEvents(vm); callHook(vm, 'beforeCreate'); initState(vm); callHook(vm, 'created'); initRender(vm); }; } function initInternalComponent (vm, options) { var opts = vm.$options = Object.create(vm.constructor.options); // doing this because it's faster than dynamic enumeration. opts.parent = options.parent; opts.propsData = options.propsData; opts._parentVnode = options._parentVnode; opts._parentListeners = options._parentListeners; opts._renderChildren = options._renderChildren; opts._componentTag = options._componentTag; opts._parentElm = options._parentElm; opts._refElm = options._refElm; if (options.render) { opts.render = options.render; opts.staticRenderFns = options.staticRenderFns; } } function resolveConstructorOptions (Ctor) { var options = Ctor.options; if (Ctor.super) { var superOptions = Ctor.super.options; var cachedSuperOptions = Ctor.superOptions; var extendOptions = Ctor.extendOptions; if (superOptions !== cachedSuperOptions) { // super option changed Ctor.superOptions = superOptions; extendOptions.render = options.render; extendOptions.staticRenderFns = options.staticRenderFns; extendOptions._scopeId = options._scopeId; options = Ctor.options = mergeOptions(superOptions, extendOptions); if (options.name) { options.components[options.name] = Ctor; } } } return options } function Vue$2 (options) { if (process.env.NODE_ENV !== 'production' && !(this instanceof Vue$2)) { warn('Vue is a constructor and should be called with the `new` keyword'); } this._init(options); } initMixin(Vue$2); stateMixin(Vue$2); eventsMixin(Vue$2); lifecycleMixin(Vue$2); renderMixin(Vue$2); /* */ function initUse (Vue) { 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 }; } /* */ function initMixin$1 (Vue) { Vue.mixin = function (mixin) { this.options = mergeOptions(this.options, mixin); }; } /* */ function initExtend (Vue) { /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var SuperId = Super.cid; var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {}); if (cachedCtors[SuperId]) { return cachedCtors[SuperId] } var name = extendOptions.name || Super.options.name; if (process.env.NODE_ENV !== 'production') { if (!/^[a-zA-Z][\w-]*$/.test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'can only contain alphanumeric characters and the hyphen, ' + 'and must start with a letter.' ); } } var Sub = function VueComponent (options) { this._init(options); }; Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions( Super.options, extendOptions ); Sub['super'] = Super; // allow further extension/mixin/plugin usage Sub.extend = Super.extend; Sub.mixin = Super.mixin; Sub.use = Super.use; // create asset registers, so extended classes // can have their private assets too. config._assetTypes.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // keep a reference to the super options at extension time. // later at instantiation we can check if Super's options have // been updated. Sub.superOptions = Super.options; Sub.extendOptions = extendOptions; // cache constructor cachedCtors[SuperId] = Sub; return Sub }; } /* */ function initAssetRegisters (Vue) { /** * Create asset registration methods. */ config._assetTypes.forEach(function (type) { Vue[type] = function ( id, definition ) { if (!definition) { return this.options[type + 's'][id] } else { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if (type === 'component' && config.isReservedTag(id)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + id ); } } if (type === 'component' && isPlainObject(definition)) { definition.name = definition.name || id; definition = this.options._base.extend(definition); } if (type === 'directive' && typeof definition === 'function') { definition = { bind: definition, update: definition }; } this.options[type + 's'][id] = definition; return definition } }; }); } /* */ var patternTypes = [String, RegExp]; function matches (pattern, name) { if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else { return pattern.test(name) } } var KeepAlive = { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes }, created: function created () { this.cache = Object.create(null); }, render: function render () { var vnode = getFirstComponentChild(this.$slots.default); if (vnode && vnode.componentOptions) { var opts = vnode.componentOptions; // check pattern var name = opts.Ctor.options.name || opts.tag; if (name && ( (this.include && !matches(this.include, name)) || (this.exclude && matches(this.exclude, name)) )) { return vnode } var key = vnode.key == null // same constructor may get registered as different local components // so cid alone is not enough (#3269) ? opts.Ctor.cid + (opts.tag ? ("::" + (opts.tag)) : '') : vnode.key; if (this.cache[key]) { vnode.child = this.cache[key].child; } else { this.cache[key] = vnode; } vnode.data.keepAlive = true; } return vnode }, destroyed: function destroyed () { var this$1 = this; for (var key in this.cache) { var vnode = this$1.cache[key]; callHook(vnode.child, 'deactivated'); vnode.child.$destroy(); } } }; var builtInComponents = { KeepAlive: KeepAlive }; /* */ function initGlobalAPI (Vue) { // config var configDef = {}; configDef.get = function () { return config; }; if (process.env.NODE_ENV !== 'production') { configDef.set = function () { warn( 'Do not replace the Vue.config object, set individual fields instead.' ); }; } Object.defineProperty(Vue, 'config', configDef); Vue.util = util; Vue.set = set$1; Vue.delete = del; Vue.nextTick = nextTick; Vue.options = Object.create(null); config._assetTypes.forEach(function (type) { Vue.options[type + 's'] = Object.create(null); }); // this is used to identify the "base" constructor to extend all plain-object // components with in Weex's multi-instance scenarios. Vue.options._base = Vue; extend(Vue.options.components, builtInComponents); initUse(Vue); initMixin$1(Vue); initExtend(Vue); initAssetRegisters(Vue); } initGlobalAPI(Vue$2); Object.defineProperty(Vue$2.prototype, '$isServer', { get: isServerRendering }); Vue$2.version = '2.1.6'; /* */ // attributes that should be using props for binding var acceptValue = makeMap('input,textarea,option,select'); var mustUseProp = function (tag, attr) { return ( (attr === 'value' && acceptValue(tag)) || (attr === 'selected' && tag === 'option') || (attr === 'checked' && tag === 'input') || (attr === 'muted' && tag === 'video') ) }; var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'); var isBooleanAttr = makeMap( 'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' + 'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' + 'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' + 'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' + 'required,reversed,scoped,seamless,selected,sortable,translate,' + 'truespeed,typemustmatch,visible' ); var xlinkNS = 'http://www.w3.org/1999/xlink'; var isXlink = function (name) { return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink' }; var getXlinkProp = function (name) { return isXlink(name) ? name.slice(6, name.length) : '' }; var isFalsyAttrValue = function (val) { return val == null || val === false }; /* */ function genClassForVnode (vnode) { var data = vnode.data; var parentNode = vnode; var childNode = vnode; while (childNode.child) { childNode = childNode.child._vnode; if (childNode.data) { data = mergeClassData(childNode.data, data); } } while ((parentNode = parentNode.parent)) { if (parentNode.data) { data = mergeClassData(data, parentNode.data); } } return genClassFromData(data) } function mergeClassData (child, parent) { return { staticClass: concat(child.staticClass, parent.staticClass), class: child.class ? [child.class, parent.class] : parent.class } } function genClassFromData (data) { var dynamicClass = data.class; var staticClass = data.staticClass; if (staticClass || dynamicClass) { return concat(staticClass, stringifyClass(dynamicClass)) } /* istanbul ignore next */ return '' } function concat (a, b) { return a ? b ? (a + ' ' + b) : a : (b || '') } function stringifyClass (value) { var res = ''; if (!value) { return res } if (typeof value === 'string') { return value } if (Array.isArray(value)) { var stringified; for (var i = 0, l = value.length; i < l; i++) { if (value[i]) { if ((stringified = stringifyClass(value[i]))) { res += stringified + ' '; } } } return res.slice(0, -1) } if (isObject(value)) { for (var key in value) { if (value[key]) { res += key + ' '; } } return res.slice(0, -1) } /* istanbul ignore next */ return res } /* */ var namespaceMap = { svg: 'http://www.w3.org/2000/svg', math: 'http://www.w3.org/1998/Math/MathML', xhtml: 'http://www.w3.org/1999/xhtml' }; var isHTMLTag = makeMap( 'html,body,base,head,link,meta,style,title,' + 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' + 'div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,' + 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' + 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' + 'embed,object,param,source,canvas,script,noscript,del,ins,' + 'caption,col,colgroup,table,thead,tbody,td,th,tr,' + 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' + 'output,progress,select,textarea,' + 'details,dialog,menu,menuitem,summary,' + 'content,element,shadow,template' ); // this map is intentionally selective, only covering SVG elements that may // contain child elements. var isSVG = makeMap( 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,' + 'font-face,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' + 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view', true ); var isReservedTag = function (tag) { return isHTMLTag(tag) || isSVG(tag) }; function getTagNamespace (tag) { if (isSVG(tag)) { return 'svg' } // basic support for MathML // note it doesn't support other MathML elements being component roots if (tag === 'math') { return 'math' } } var unknownElementCache = Object.create(null); function isUnknownElement (tag) { /* istanbul ignore if */ if (!inBrowser) { return true } if (isReservedTag(tag)) { return false } tag = tag.toLowerCase(); /* istanbul ignore if */ if (unknownElementCache[tag] != null) { return unknownElementCache[tag] } var el = document.createElement(tag); if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return (unknownElementCache[tag] = ( el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement )) } else { return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString())) } } /* */ /** * Query an element selector if it's not an element already. */ function query (el) { if (typeof el === 'string') { var selector = el; el = document.querySelector(el); if (!el) { process.env.NODE_ENV !== 'production' && warn( 'Cannot find element: ' + selector ); return document.createElement('div') } } return el } /* */ function createElement$1 (tagName, vnode) { var elm = document.createElement(tagName); if (tagName !== 'select') { return elm } if (vnode.data && vnode.data.attrs && 'multiple' in vnode.data.attrs) { elm.setAttribute('multiple', 'multiple'); } return elm } function createElementNS (namespace, tagName) { return document.createElementNS(namespaceMap[namespace], tagName) } function createTextNode (text) { return document.createTextNode(text) } function createComment (text) { return document.createComment(text) } function insertBefore (parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild (node, child) { node.removeChild(child); } function appendChild (node, child) { node.appendChild(child); } function parentNode (node) { return node.parentNode } function nextSibling (node) { return node.nextSibling } function tagName (node) { return node.tagName } function setTextContent (node, text) { node.textContent = text; } function setAttribute (node, key, val) { node.setAttribute(key, val); } var nodeOps = Object.freeze({ createElement: createElement$1, createElementNS: createElementNS, createTextNode: createTextNode, createComment: createComment, insertBefore: insertBefore, removeChild: removeChild, appendChild: appendChild, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent, setAttribute: setAttribute }); /* */ var ref = { create: function create (_, vnode) { registerRef(vnode); }, update: function update (oldVnode, vnode) { if (oldVnode.data.ref !== vnode.data.ref) { registerRef(oldVnode, true); registerRef(vnode); } }, destroy: function destroy (vnode) { registerRef(vnode, true); } }; function registerRef (vnode, isRemoval) { var key = vnode.data.ref; if (!key) { return } var vm = vnode.context; var ref = vnode.child || vnode.elm; var refs = vm.$refs; if (isRemoval) { if (Array.isArray(refs[key])) { remove$1(refs[key], ref); } else if (refs[key] === ref) { refs[key] = undefined; } } else { if (vnode.data.refInFor) { if (Array.isArray(refs[key]) && refs[key].indexOf(ref) < 0) { refs[key].push(ref); } else { refs[key] = [ref]; } } else { refs[key] = ref; } } } /** * Virtual DOM patching algorithm based on Snabbdom by * Simon Friis Vindum (@paldepind) * Licensed under the MIT License * https://github.com/paldepind/snabbdom/blob/master/LICENSE * * modified by Evan You (@yyx990803) * /* * Not type-checking this because this file is perf-critical and the cost * of making flow understand it is not worth it. */ var emptyNode = new VNode('', {}, []); var hooks$1 = ['create', 'activate', 'update', 'remove', 'destroy']; function isUndef (s) { return s == null } function isDef (s) { return s != null } function sameVnode (vnode1, vnode2) { return ( vnode1.key === vnode2.key && vnode1.tag === vnode2.tag && vnode1.isComment === vnode2.isComment && !vnode1.data === !vnode2.data ) } function createKeyToOldIdx (children, beginIdx, endIdx) { var i, key; var map = {}; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) { map[key] = i; } } return map } function createPatchFunction (backend) { var i, j; var cbs = {}; var modules = backend.modules; var nodeOps = backend.nodeOps; for (i = 0; i < hooks$1.length; ++i) { cbs[hooks$1[i]] = []; for (j = 0; j < modules.length; ++j) { if (modules[j][hooks$1[i]] !== undefined) { cbs[hooks$1[i]].push(modules[j][hooks$1[i]]); } } } function emptyNodeAt (elm) { return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm) } function createRmCb (childElm, listeners) { function remove$$1 () { if (--remove$$1.listeners === 0) { removeElement(childElm); } } remove$$1.listeners = listeners; return remove$$1 } function removeElement (el) { var parent = nodeOps.parentNode(el); // element may have already been removed due to v-html if (parent) { nodeOps.removeChild(parent, el); } } var inPre = 0; function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) { vnode.isRootInsert = !nested; // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return } var data = vnode.data; var children = vnode.children; var tag = vnode.tag; if (isDef(tag)) { if (process.env.NODE_ENV !== 'production') { if (data && data.pre) { inPre++; } if ( !inPre && !vnode.ns && !(config.ignoredElements && config.ignoredElements.indexOf(tag) > -1) && config.isUnknownElement(tag) ) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ); } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode); setScope(vnode); /* istanbul ignore if */ { createChildren(vnode, children, insertedVnodeQueue); if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue); } insert(parentElm, vnode.elm, refElm); } if (process.env.NODE_ENV !== 'production' && data && data.pre) { inPre--; } } else if (vnode.isComment) { vnode.elm = nodeOps.createComment(vnode.text); insert(parentElm, vnode.elm, refElm); } else { vnode.elm = nodeOps.createTextNode(vnode.text); insert(parentElm, vnode.elm, refElm); } } function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i = vnode.data; if (isDef(i)) { var isReactivated = isDef(vnode.child) && i.keepAlive; if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */, parentElm, refElm); } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.child)) { initComponent(vnode, insertedVnodeQueue); if (isReactivated) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm); } return true } } } function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i; // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. var innerNode = vnode; while (innerNode.child) { innerNode = innerNode.child._vnode; if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode); } insertedVnodeQueue.push(innerNode); break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm); } function insert (parent, elm, ref) { if (parent) { if (ref) { nodeOps.insertBefore(parent, elm, ref); } else { nodeOps.appendChild(parent, elm); } } } function createChildren (vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { for (var i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true); } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text)); } } function isPatchable (vnode) { while (vnode.child) { vnode = vnode.child._vnode; } return isDef(vnode.tag) } function invokeCreateHooks (vnode, insertedVnodeQueue) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, vnode); } i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (i.create) { i.create(emptyNode, vnode); } if (i.insert) { insertedVnodeQueue.push(vnode); } } } function initComponent (vnode, insertedVnodeQueue) { if (vnode.data.pendingInsert) { insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert); } vnode.elm = vnode.child.$el; if (isPatchable(vnode)) { invokeCreateHooks(vnode, insertedVnodeQueue); setScope(vnode); } else { // empty component root. // skip all element-related modules except for ref (#3455) registerRef(vnode); // make sure to invoke the insert hook insertedVnodeQueue.push(vnode); } } // set scope id attribute for scoped CSS. // this is implemented as a special case to avoid the overhead // of going through the normal attribute patching process. function setScope (vnode) { var i; if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } if (isDef(i = activeInstance) && i !== vnode.context && isDef(i = i.$options._scopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } } function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm); } } function invokeDestroyHook (vnode) { var i, j; var data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); } for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); } } if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } } function removeVnodes (parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.tag)) { removeAndInvokeRemoveHook(ch); invokeDestroyHook(ch); } else { // Text node nodeOps.removeChild(parentElm, ch.elm); } } } } function removeAndInvokeRemoveHook (vnode, rm) { if (rm || isDef(vnode.data)) { var listeners = cbs.remove.length + 1; if (!rm) { // directly removing rm = createRmCb(vnode.elm, listeners); } else { // we have a recursively passed down rm callback // increase the listeners count rm.listeners += listeners; } // recursively invoke hooks on child component root node if (isDef(i = vnode.child) && isDef(i = i._vnode) && isDef(i.data)) { removeAndInvokeRemoveHook(i, rm); } for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](vnode, rm); } if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) { i(vnode, rm); } else { rm(); } } else { removeElement(vnode.elm); } } function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { var oldStartIdx = 0; var newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, elmToMove, refElm; // removeOnly is a special flag used only by <transition-group> // to ensure removed elements stay in correct relative positions // during leaving transitions var canMove = !removeOnly; while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); } idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : null; if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } else { elmToMove = oldCh[idxInOld]; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !elmToMove) { warn( 'It seems there are duplicate keys that is causing an update error. ' + 'Make sure each v-for item has a unique key.' ); } if (sameVnode(elmToMove, newStartVnode)) { patchVnode(elmToMove, newStartVnode, insertedVnodeQueue); oldCh[idxInOld] = undefined; canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } else { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } } } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); } } function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) { if (oldVnode === vnode) { return } // reuse element for static trees. // note we only do this if the vnode is cloned - // if the new node is not cloned it means the render functions have been // reset by the hot-reload-api and we need to do a proper re-render. if (vnode.isStatic && oldVnode.isStatic && vnode.key === oldVnode.key && (vnode.isCloned || vnode.isOnce)) { vnode.elm = oldVnode.elm; vnode.child = oldVnode.child; return } var i; var data = vnode.data; var hasData = isDef(data); if (hasData && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode); } var elm = vnode.elm = oldVnode.elm; var oldCh = oldVnode.children; var ch = vnode.children; if (hasData && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); } if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); } } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); } } else if (isDef(ch)) { if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text); } if (hasData) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); } } } function invokeInsertHook (vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (initial && vnode.parent) { vnode.parent.data.pendingInsert = queue; } else { for (var i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]); } } } var bailed = false; // list of modules that can skip create hook during hydration because they // are already rendered on the client or has no need for initialization var isRenderedModule = makeMap('attrs,style,class,staticClass,staticStyle,key'); // Note: this is a browser-only function so we can assume elms are DOM nodes. function hydrate (elm, vnode, insertedVnodeQueue) { if (process.env.NODE_ENV !== 'production') { if (!assertNodeMatch(elm, vnode)) { return false } } vnode.elm = elm; var tag = vnode.tag; var data = vnode.data; var children = vnode.children; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); } if (isDef(i = vnode.child)) { // child component. it should have hydrated its own tree. initComponent(vnode, insertedVnodeQueue); return true } } if (isDef(tag)) { if (isDef(children)) { // empty element, allow client to pick up and populate children if (!elm.hasChildNodes()) { createChildren(vnode, children, insertedVnodeQueue); } else { var childrenMatch = true; var childNode = elm.firstChild; for (var i$1 = 0; i$1 < children.length; i$1++) { if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue)) { childrenMatch = false; break } childNode = childNode.nextSibling; } // if childNode is not null, it means the actual childNodes list is // longer than the virtual children list. if (!childrenMatch || childNode) { if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined' && !bailed) { bailed = true; console.warn('Parent: ', elm); console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children); } return false } } } if (isDef(data)) { for (var key in data) { if (!isRenderedModule(key)) { invokeCreateHooks(vnode, insertedVnodeQueue); break } } } } return true } function assertNodeMatch (node, vnode) { if (vnode.tag) { return ( vnode.tag.indexOf('vue-component') === 0 || vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase()) ) } else { return _toString(vnode.text) === node.data } } return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) { if (!vnode) { if (oldVnode) { invokeDestroyHook(oldVnode); } return } var elm, parent; var isInitialPatch = false; var insertedVnodeQueue = []; if (!oldVnode) { // empty mount (likely as component), create new root element isInitialPatch = true; createElm(vnode, insertedVnodeQueue, parentElm, refElm); } else { var isRealElement = isDef(oldVnode.nodeType); if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly); } else { if (isRealElement) { // mounting to a real element // check if this is server-rendered content and if we can perform // a successful hydration. if (oldVnode.nodeType === 1 && oldVnode.hasAttribute('server-rendered')) { oldVnode.removeAttribute('server-rendered'); hydrating = true; } if (hydrating) { if (hydrate(oldVnode, vnode, insertedVnodeQueue)) { invokeInsertHook(vnode, insertedVnodeQueue, true); return oldVnode } else if (process.env.NODE_ENV !== 'production') { warn( 'The client-side rendered virtual DOM tree is not matching ' + 'server-rendered content. This is likely caused by incorrect ' + 'HTML markup, for example nesting block-level elements inside ' + '<p>, or missing <tbody>. Bailing hydration and performing ' + 'full client-side render.' ); } } // either not server-rendered, or hydration failed. // create an empty node and replace it oldVnode = emptyNodeAt(oldVnode); } // replacing existing element elm = oldVnode.elm; parent = nodeOps.parentNode(elm); createElm(vnode, insertedVnodeQueue, parent, nodeOps.nextSibling(elm)); if (vnode.parent) { // component root element replaced. // update parent placeholder node element, recursively var ancestor = vnode.parent; while (ancestor) { ancestor.elm = vnode.elm; ancestor = ancestor.parent; } if (isPatchable(vnode)) { for (var i = 0; i < cbs.create.length; ++i) { cbs.create[i](emptyNode, vnode.parent); } } } if (parent !== null) { removeVnodes(parent, [oldVnode], 0, 0); } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode); } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch); return vnode.elm } } /* */ var directives = { create: updateDirectives, update: updateDirectives, destroy: function unbindDirectives (vnode) { updateDirectives(vnode, emptyNode); } }; function updateDirectives (oldVnode, vnode) { if (oldVnode.data.directives || vnode.data.directives) { _update(oldVnode, vnode); } } function _update (oldVnode, vnode) { var isCreate = oldVnode === emptyNode; var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context); var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context); var dirsWithInsert = []; var dirsWithPostpatch = []; var key, oldDir, dir; for (key in newDirs) { oldDir = oldDirs[key]; dir = newDirs[key]; if (!oldDir) { // new directive, bind callHook$1(dir, 'bind', vnode, oldVnode); if (dir.def && dir.def.inserted) { dirsWithInsert.push(dir); } } else { // existing directive, update dir.oldValue = oldDir.value; callHook$1(dir, 'update', vnode, oldVnode); if (dir.def && dir.def.componentUpdated) { dirsWithPostpatch.push(dir); } } } if (dirsWithInsert.length) { var callInsert = function () { for (var i = 0; i < dirsWithInsert.length; i++) { callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode); } }; if (isCreate) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert, 'dir-insert'); } else { callInsert(); } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', function () { for (var i = 0; i < dirsWithPostpatch.length; i++) { callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode); } }, 'dir-postpatch'); } if (!isCreate) { for (key in oldDirs) { if (!newDirs[key]) { // no longer present, unbind callHook$1(oldDirs[key], 'unbind', oldVnode); } } } } var emptyModifiers = Object.create(null); function normalizeDirectives$1 ( dirs, vm ) { var res = Object.create(null); if (!dirs) { return res } var i, dir; for (i = 0; i < dirs.length; i++) { dir = dirs[i]; if (!dir.modifiers) { dir.modifiers = emptyModifiers; } res[getRawDirName(dir)] = dir; dir.def = resolveAsset(vm.$options, 'directives', dir.name, true); } return res } function getRawDirName (dir) { return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.'))) } function callHook$1 (dir, hook, vnode, oldVnode) { var fn = dir.def && dir.def[hook]; if (fn) { fn(vnode.elm, dir, vnode, oldVnode); } } var baseModules = [ ref, directives ]; /* */ function updateAttrs (oldVnode, vnode) { if (!oldVnode.data.attrs && !vnode.data.attrs) { return } var key, cur, old; var elm = vnode.elm; var oldAttrs = oldVnode.data.attrs || {}; var attrs = vnode.data.attrs || {}; // clone observed objects, as the user probably wants to mutate it if (attrs.__ob__) { attrs = vnode.data.attrs = extend({}, attrs); } for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { setAttr(elm, key, cur); } } // #4391: in IE9, setting type can reset value for input[type=radio] /* istanbul ignore if */ if (isIE9 && attrs.value !== oldAttrs.value) { setAttr(elm, 'value', attrs.value); } for (key in oldAttrs) { if (attrs[key] == null) { if (isXlink(key)) { elm.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else if (!isEnumeratedAttr(key)) { elm.removeAttribute(key); } } } } function setAttr (el, key, value) { if (isBooleanAttr(key)) { // set attribute for blank value // e.g. <option disabled>Select one</option> if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { el.setAttribute(key, key); } } else if (isEnumeratedAttr(key)) { el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true'); } else if (isXlink(key)) { if (isFalsyAttrValue(value)) { el.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else { el.setAttributeNS(xlinkNS, key, value); } } else { if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { el.setAttribute(key, value); } } } var attrs = { create: updateAttrs, update: updateAttrs }; /* */ function updateClass (oldVnode, vnode) { var el = vnode.elm; var data = vnode.data; var oldData = oldVnode.data; if (!data.staticClass && !data.class && (!oldData || (!oldData.staticClass && !oldData.class))) { return } var cls = genClassForVnode(vnode); // handle transition classes var transitionClass = el._transitionClasses; if (transitionClass) { cls = concat(cls, stringifyClass(transitionClass)); } // set the class if (cls !== el._prevClass) { el.setAttribute('class', cls); el._prevClass = cls; } } var klass = { create: updateClass, update: updateClass }; /* */ var target; function add$1 (event, handler, once, capture) { if (once) { var oldHandler = handler; handler = function (ev) { remove$2(event, handler, capture); arguments.length === 1 ? oldHandler(ev) : oldHandler.apply(null, arguments); }; } target.addEventListener(event, handler, capture); } function remove$2 (event, handler, capture) { target.removeEventListener(event, handler, capture); } function updateDOMListeners (oldVnode, vnode) { if (!oldVnode.data.on && !vnode.data.on) { return } var on = vnode.data.on || {}; var oldOn = oldVnode.data.on || {}; target = vnode.elm; updateListeners(on, oldOn, add$1, remove$2, vnode.context); } var events = { create: updateDOMListeners, update: updateDOMListeners }; /* */ function updateDOMProps (oldVnode, vnode) { if (!oldVnode.data.domProps && !vnode.data.domProps) { return } var key, cur; var elm = vnode.elm; var oldProps = oldVnode.data.domProps || {}; var props = vnode.data.domProps || {}; // clone observed objects, as the user probably wants to mutate it if (props.__ob__) { props = vnode.data.domProps = extend({}, props); } for (key in oldProps) { if (props[key] == null) { elm[key] = ''; } } for (key in props) { cur = props[key]; // ignore children if the node has textContent or innerHTML, // as these will throw away existing DOM nodes and cause removal errors // on subsequent patches (#3360) if (key === 'textContent' || key === 'innerHTML') { if (vnode.children) { vnode.children.length = 0; } if (cur === oldProps[key]) { continue } } if (key === 'value') { // store value as _value as well since // non-string values will be stringified elm._value = cur; // avoid resetting cursor position when value is the same var strCur = cur == null ? '' : String(cur); if (!elm.composing && ( (document.activeElement !== elm && elm.value !== strCur) || isValueChanged(vnode, strCur) )) { elm.value = strCur; } } else { elm[key] = cur; } } } function isValueChanged (vnode, newVal) { var value = vnode.elm.value; var modifiers = vnode.elm._vModifiers; // injected by v-model runtime if ((modifiers && modifiers.number) || vnode.elm.type === 'number') { return toNumber(value) !== toNumber(newVal) } if (modifiers && modifiers.trim) { return value.trim() !== newVal.trim() } return value !== newVal } var domProps = { create: updateDOMProps, update: updateDOMProps }; /* */ var parseStyleText = cached(function (cssText) { var res = {}; var listDelimiter = /;(?![^(]*\))/g; var propertyDelimiter = /:(.+)/; cssText.split(listDelimiter).forEach(function (item) { if (item) { var tmp = item.split(propertyDelimiter); tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); } }); return res }); // merge static and dynamic style data on the same vnode function normalizeStyleData (data) { var style = normalizeStyleBinding(data.style); // static style is pre-processed into an object during compilation // and is always a fresh object, so it's safe to merge into it return data.staticStyle ? extend(data.staticStyle, style) : style } // normalize possible array / string values into Object function normalizeStyleBinding (bindingStyle) { if (Array.isArray(bindingStyle)) { return toObject(bindingStyle) } if (typeof bindingStyle === 'string') { return parseStyleText(bindingStyle) } return bindingStyle } /** * parent component style should be after child's * so that parent component's style could override it */ function getStyle (vnode, checkChild) { var res = {}; var styleData; if (checkChild) { var childNode = vnode; while (childNode.child) { childNode = childNode.child._vnode; if (childNode.data && (styleData = normalizeStyleData(childNode.data))) { extend(res, styleData); } } } if ((styleData = normalizeStyleData(vnode.data))) { extend(res, styleData); } var parentNode = vnode; while ((parentNode = parentNode.parent)) { if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) { extend(res, styleData); } } return res } /* */ var cssVarRE = /^--/; var importantRE = /\s*!important$/; var setProp = function (el, name, val) { /* istanbul ignore if */ if (cssVarRE.test(name)) { el.style.setProperty(name, val); } else if (importantRE.test(val)) { el.style.setProperty(name, val.replace(importantRE, ''), 'important'); } else { el.style[normalize(name)] = val; } }; var prefixes = ['Webkit', 'Moz', 'ms']; var testEl; var normalize = cached(function (prop) { testEl = testEl || document.createElement('div'); prop = camelize(prop); if (prop !== 'filter' && (prop in testEl.style)) { return prop } var upper = prop.charAt(0).toUpperCase() + prop.slice(1); for (var i = 0; i < prefixes.length; i++) { var prefixed = prefixes[i] + upper; if (prefixed in testEl.style) { return prefixed } } }); function updateStyle (oldVnode, vnode) { var data = vnode.data; var oldData = oldVnode.data; if (!data.staticStyle && !data.style && !oldData.staticStyle && !oldData.style) { return } var cur, name; var el = vnode.elm; var oldStaticStyle = oldVnode.data.staticStyle; var oldStyleBinding = oldVnode.data.style || {}; // if static style exists, stylebinding already merged into it when doing normalizeStyleData var oldStyle = oldStaticStyle || oldStyleBinding; var style = normalizeStyleBinding(vnode.data.style) || {}; vnode.data.style = style.__ob__ ? extend({}, style) : style; var newStyle = getStyle(vnode, true); for (name in oldStyle) { if (newStyle[name] == null) { setProp(el, name, ''); } } for (name in newStyle) { cur = newStyle[name]; if (cur !== oldStyle[name]) { // ie9 setting to null has no effect, must use empty string setProp(el, name, cur == null ? '' : cur); } } } var style = { create: updateStyle, update: updateStyle }; /* */ /** * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function addClass (el, cls) { /* istanbul ignore if */ if (!cls || !cls.trim()) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); }); } else { el.classList.add(cls); } } else { var cur = ' ' + el.getAttribute('class') + ' '; if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()); } } } /** * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function removeClass (el, cls) { /* istanbul ignore if */ if (!cls || !cls.trim()) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); }); } else { el.classList.remove(cls); } } else { var cur = ' ' + el.getAttribute('class') + ' '; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } el.setAttribute('class', cur.trim()); } } /* */ var hasTransition = inBrowser && !isIE9; var TRANSITION = 'transition'; var ANIMATION = 'animation'; // Transition property/event sniffing var transitionProp = 'transition'; var transitionEndEvent = 'transitionend'; var animationProp = 'animation'; var animationEndEvent = 'animationend'; if (hasTransition) { /* istanbul ignore if */ if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) { transitionProp = 'WebkitTransition'; transitionEndEvent = 'webkitTransitionEnd'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) { animationProp = 'WebkitAnimation'; animationEndEvent = 'webkitAnimationEnd'; } } var raf = (inBrowser && window.requestAnimationFrame) || setTimeout; function nextFrame (fn) { raf(function () { raf(fn); }); } function addTransitionClass (el, cls) { (el._transitionClasses || (el._transitionClasses = [])).push(cls); addClass(el, cls); } function removeTransitionClass (el, cls) { if (el._transitionClasses) { remove$1(el._transitionClasses, cls); } removeClass(el, cls); } function whenTransitionEnds ( el, expectedType, cb ) { var ref = getTransitionInfo(el, expectedType); var type = ref.type; var timeout = ref.timeout; var propCount = ref.propCount; if (!type) { return cb() } var event = type === TRANSITION ? transitionEndEvent : animationEndEvent; var ended = 0; var end = function () { el.removeEventListener(event, onEnd); cb(); }; var onEnd = function (e) { if (e.target === el) { if (++ended >= propCount) { end(); } } }; setTimeout(function () { if (ended < propCount) { end(); } }, timeout + 1); el.addEventListener(event, onEnd); } var transformRE = /\b(transform|all)(,|$)/; function getTransitionInfo (el, expectedType) { var styles = window.getComputedStyle(el); var transitioneDelays = styles[transitionProp + 'Delay'].split(', '); var transitionDurations = styles[transitionProp + 'Duration'].split(', '); var transitionTimeout = getTimeout(transitioneDelays, transitionDurations); var animationDelays = styles[animationProp + 'Delay'].split(', '); var animationDurations = styles[animationProp + 'Duration'].split(', '); var animationTimeout = getTimeout(animationDelays, animationDurations); var type; var timeout = 0; var propCount = 0; /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION; timeout = transitionTimeout; propCount = transitionDurations.length; } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION; timeout = animationTimeout; propCount = animationDurations.length; } } else { timeout = Math.max(transitionTimeout, animationTimeout); type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; } var hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']); return { type: type, timeout: timeout, propCount: propCount, hasTransform: hasTransform } } function getTimeout (delays, durations) { /* istanbul ignore next */ while (delays.length < durations.length) { delays = delays.concat(delays); } return Math.max.apply(null, durations.map(function (d, i) { return toMs(d) + toMs(delays[i]) })) } function toMs (s) { return Number(s.slice(0, -1)) * 1000 } /* */ function enter (vnode, toggleDisplay) { var el = vnode.elm; // call leave callback now if (el._leaveCb) { el._leaveCb.cancelled = true; el._leaveCb(); } var data = resolveTransition(vnode.data.transition); if (!data) { return } /* istanbul ignore if */ if (el._enterCb || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var enterClass = data.enterClass; var enterActiveClass = data.enterActiveClass; var appearClass = data.appearClass; var appearActiveClass = data.appearActiveClass; var beforeEnter = data.beforeEnter; var enter = data.enter; var afterEnter = data.afterEnter; var enterCancelled = data.enterCancelled; var beforeAppear = data.beforeAppear; var appear = data.appear; var afterAppear = data.afterAppear; var appearCancelled = data.appearCancelled; // activeInstance will always be the <transition> component managing this // transition. One edge case to check is when the <transition> is placed // as the root node of a child component. In that case we need to check // <transition>'s parent for appear check. var context = activeInstance; var transitionNode = activeInstance.$vnode; while (transitionNode && transitionNode.parent) { transitionNode = transitionNode.parent; context = transitionNode.context; } var isAppear = !context._isMounted || !vnode.isRootInsert; if (isAppear && !appear && appear !== '') { return } var startClass = isAppear ? appearClass : enterClass; var activeClass = isAppear ? appearActiveClass : enterActiveClass; var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter; var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter; var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter; var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled; var expectsCSS = css !== false && !isIE9; var userWantsControl = enterHook && // enterHook may be a bound method which exposes // the length of original fn as _length (enterHook._length || enterHook.length) > 1; var cb = el._enterCb = once(function () { if (expectsCSS) { removeTransitionClass(el, activeClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, startClass); } enterCancelledHook && enterCancelledHook(el); } else { afterEnterHook && afterEnterHook(el); } el._enterCb = null; }); if (!vnode.data.show) { // remove pending leave element on enter by injecting an insert hook mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () { var parent = el.parentNode; var pendingNode = parent && parent._pending && parent._pending[vnode.key]; if (pendingNode && pendingNode.context === vnode.context && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb) { pendingNode.elm._leaveCb(); } enterHook && enterHook(el, cb); }, 'transition-insert'); } // start enter transition beforeEnterHook && beforeEnterHook(el); if (expectsCSS) { addTransitionClass(el, startClass); addTransitionClass(el, activeClass); nextFrame(function () { removeTransitionClass(el, startClass); if (!cb.cancelled && !userWantsControl) { whenTransitionEnds(el, type, cb); } }); } if (vnode.data.show) { toggleDisplay && toggleDisplay(); enterHook && enterHook(el, cb); } if (!expectsCSS && !userWantsControl) { cb(); } } function leave (vnode, rm) { var el = vnode.elm; // call enter callback now if (el._enterCb) { el._enterCb.cancelled = true; el._enterCb(); } var data = resolveTransition(vnode.data.transition); if (!data) { return rm() } /* istanbul ignore if */ if (el._leaveCb || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var leaveClass = data.leaveClass; var leaveActiveClass = data.leaveActiveClass; var beforeLeave = data.beforeLeave; var leave = data.leave; var afterLeave = data.afterLeave; var leaveCancelled = data.leaveCancelled; var delayLeave = data.delayLeave; var expectsCSS = css !== false && !isIE9; var userWantsControl = leave && // leave hook may be a bound method which exposes // the length of original fn as _length (leave._length || leave.length) > 1; var cb = el._leaveCb = once(function () { if (el.parentNode && el.parentNode._pending) { el.parentNode._pending[vnode.key] = null; } if (expectsCSS) { removeTransitionClass(el, leaveActiveClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, leaveClass); } leaveCancelled && leaveCancelled(el); } else { rm(); afterLeave && afterLeave(el); } el._leaveCb = null; }); if (delayLeave) { delayLeave(performLeave); } else { performLeave(); } function performLeave () { // the delayed leave may have already been cancelled if (cb.cancelled) { return } // record leaving element if (!vnode.data.show) { (el.parentNode._pending || (el.parentNode._pending = {}))[vnode.key] = vnode; } beforeLeave && beforeLeave(el); if (expectsCSS) { addTransitionClass(el, leaveClass); addTransitionClass(el, leaveActiveClass); nextFrame(function () { removeTransitionClass(el, leaveClass); if (!cb.cancelled && !userWantsControl) { whenTransitionEnds(el, type, cb); } }); } leave && leave(el, cb); if (!expectsCSS && !userWantsControl) { cb(); } } } function resolveTransition (def$$1) { if (!def$$1) { return } /* istanbul ignore else */ if (typeof def$$1 === 'object') { var res = {}; if (def$$1.css !== false) { extend(res, autoCssTransition(def$$1.name || 'v')); } extend(res, def$$1); return res } else if (typeof def$$1 === 'string') { return autoCssTransition(def$$1) } } var autoCssTransition = cached(function (name) { return { enterClass: (name + "-enter"), leaveClass: (name + "-leave"), appearClass: (name + "-enter"), enterActiveClass: (name + "-enter-active"), leaveActiveClass: (name + "-leave-active"), appearActiveClass: (name + "-enter-active") } }); function once (fn) { var called = false; return function () { if (!called) { called = true; fn(); } } } function _enter (_, vnode) { if (!vnode.data.show) { enter(vnode); } } var transition = inBrowser ? { create: _enter, activate: _enter, remove: function remove (vnode, rm) { /* istanbul ignore else */ if (!vnode.data.show) { leave(vnode, rm); } else { rm(); } } } : {}; var platformModules = [ attrs, klass, events, domProps, style, transition ]; /* */ // the directive module should be applied last, after all // built-in modules have been applied. var modules = platformModules.concat(baseModules); var patch$1 = createPatchFunction({ nodeOps: nodeOps, modules: modules }); /** * Not type checking this file because flow doesn't like attaching * properties to Elements. */ var modelableTagRE = /^input|select|textarea|vue-component-[0-9]+(-[0-9a-zA-Z_-]*)?$/; /* istanbul ignore if */ if (isIE9) { // http://www.matts411.com/post/internet-explorer-9-oninput/ document.addEventListener('selectionchange', function () { var el = document.activeElement; if (el && el.vmodel) { trigger(el, 'input'); } }); } var model = { inserted: function inserted (el, binding, vnode) { if (process.env.NODE_ENV !== 'production') { if (!modelableTagRE.test(vnode.tag)) { warn( "v-model is not supported on element type: <" + (vnode.tag) + ">. " + 'If you are working with contenteditable, it\'s recommended to ' + 'wrap a library dedicated for that purpose inside a custom component.', vnode.context ); } } if (vnode.tag === 'select') { var cb = function () { setSelected(el, binding, vnode.context); }; cb(); /* istanbul ignore if */ if (isIE || isEdge) { setTimeout(cb, 0); } } else if (vnode.tag === 'textarea' || el.type === 'text') { el._vModifiers = binding.modifiers; if (!binding.modifiers.lazy) { if (!isAndroid) { el.addEventListener('compositionstart', onCompositionStart); el.addEventListener('compositionend', onCompositionEnd); } /* istanbul ignore if */ if (isIE9) { el.vmodel = true; } } } }, componentUpdated: function componentUpdated (el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); // in case the options rendered by v-for have changed, // it's possible that the value is out-of-sync with the rendered options. // detect such cases and filter out values that no longer has a matching // option in the DOM. var needReset = el.multiple ? binding.value.some(function (v) { return hasNoMatchingOption(v, el.options); }) : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, el.options); if (needReset) { trigger(el, 'change'); } } } }; function setSelected (el, binding, vm) { var value = binding.value; var isMultiple = el.multiple; if (isMultiple && !Array.isArray(value)) { process.env.NODE_ENV !== 'production' && warn( "<select multiple v-model=\"" + (binding.expression) + "\"> " + "expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)), vm ); return } var selected, option; for (var i = 0, l = el.options.length; i < l; i++) { option = el.options[i]; if (isMultiple) { selected = looseIndexOf(value, getValue(option)) > -1; if (option.selected !== selected) { option.selected = selected; } } else { if (looseEqual(getValue(option), value)) { if (el.selectedIndex !== i) { el.selectedIndex = i; } return } } } if (!isMultiple) { el.selectedIndex = -1; } } function hasNoMatchingOption (value, options) { for (var i = 0, l = options.length; i < l; i++) { if (looseEqual(getValue(options[i]), value)) { return false } } return true } function getValue (option) { return '_value' in option ? option._value : option.value } function onCompositionStart (e) { e.target.composing = true; } function onCompositionEnd (e) { e.target.composing = false; trigger(e.target, 'input'); } function trigger (el, type) { var e = document.createEvent('HTMLEvents'); e.initEvent(type, true, true); el.dispatchEvent(e); } /* */ // recursively search for possible transition defined inside the component root function locateNode (vnode) { return vnode.child && (!vnode.data || !vnode.data.transition) ? locateNode(vnode.child._vnode) : vnode } var show = { bind: function bind (el, ref, vnode) { var value = ref.value; vnode = locateNode(vnode); var transition = vnode.data && vnode.data.transition; var originalDisplay = el.__vOriginalDisplay = el.style.display === 'none' ? '' : el.style.display; if (value && transition && !isIE9) { vnode.data.show = true; enter(vnode, function () { el.style.display = originalDisplay; }); } else { el.style.display = value ? originalDisplay : 'none'; } }, update: function update (el, ref, vnode) { var value = ref.value; var oldValue = ref.oldValue; /* istanbul ignore if */ if (value === oldValue) { return } vnode = locateNode(vnode); var transition = vnode.data && vnode.data.transition; if (transition && !isIE9) { vnode.data.show = true; if (value) { enter(vnode, function () { el.style.display = el.__vOriginalDisplay; }); } else { leave(vnode, function () { el.style.display = 'none'; }); } } else { el.style.display = value ? el.__vOriginalDisplay : 'none'; } } }; var platformDirectives = { model: model, show: show }; /* */ // Provides transition support for a single element/component. // supports transition mode (out-in / in-out) var transitionProps = { name: String, appear: Boolean, css: Boolean, mode: String, type: String, enterClass: String, leaveClass: String, enterActiveClass: String, leaveActiveClass: String, appearClass: String, appearActiveClass: String }; // in case the child is also an abstract component, e.g. <keep-alive> // we want to recursively retrieve the real component to be rendered function getRealChild (vnode) { var compOptions = vnode && vnode.componentOptions; if (compOptions && compOptions.Ctor.options.abstract) { return getRealChild(getFirstComponentChild(compOptions.children)) } else { return vnode } } function extractTransitionData (comp) { var data = {}; var options = comp.$options; // props for (var key in options.propsData) { data[key] = comp[key]; } // events. // extract listeners and pass them directly to the transition methods var listeners = options._parentListeners; for (var key$1 in listeners) { data[camelize(key$1)] = listeners[key$1].fn; } return data } function placeholder (h, rawChild) { return /\d-keep-alive$/.test(rawChild.tag) ? h('keep-alive') : null } function hasParentTransition (vnode) { while ((vnode = vnode.parent)) { if (vnode.data.transition) { return true } } } var Transition = { name: 'transition', props: transitionProps, abstract: true, render: function render (h) { var this$1 = this; var children = this.$slots.default; if (!children) { return } // filter out text nodes (possible whitespaces) children = children.filter(function (c) { return c.tag; }); /* istanbul ignore if */ if (!children.length) { return } // warn multiple elements if (process.env.NODE_ENV !== 'production' && children.length > 1) { warn( '<transition> can only be used on a single element. Use ' + '<transition-group> for lists.', this.$parent ); } var mode = this.mode; // warn invalid mode if (process.env.NODE_ENV !== 'production' && mode && mode !== 'in-out' && mode !== 'out-in') { warn( 'invalid <transition> mode: ' + mode, this.$parent ); } var rawChild = children[0]; // if this is a component root node and the component's // parent container node also has transition, skip. if (hasParentTransition(this.$vnode)) { return rawChild } // apply transition data to child // use getRealChild() to ignore abstract components e.g. keep-alive var child = getRealChild(rawChild); /* istanbul ignore if */ if (!child) { return rawChild } if (this._leaving) { return placeholder(h, rawChild) } var key = child.key = child.key == null || child.isStatic ? ("__v" + (child.tag + this._uid) + "__") : child.key; var data = (child.data || (child.data = {})).transition = extractTransitionData(this); var oldRawChild = this._vnode; var oldChild = getRealChild(oldRawChild); // mark v-show // so that the transition module can hand over the control to the directive if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) { child.data.show = true; } if (oldChild && oldChild.data && oldChild.key !== key) { // replace old child transition data with fresh one // important for dynamic transitions! var oldData = oldChild.data.transition = extend({}, data); // handle transition mode if (mode === 'out-in') { // return placeholder node and queue update when leave finishes this._leaving = true; mergeVNodeHook(oldData, 'afterLeave', function () { this$1._leaving = false; this$1.$forceUpdate(); }, key); return placeholder(h, rawChild) } else if (mode === 'in-out') { var delayedLeave; var performLeave = function () { delayedLeave(); }; mergeVNodeHook(data, 'afterEnter', performLeave, key); mergeVNodeHook(data, 'enterCancelled', performLeave, key); mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; }, key); } } return rawChild } }; /* */ // Provides transition support for list items. // supports move transitions using the FLIP technique. // Because the vdom's children update algorithm is "unstable" - i.e. // it doesn't guarantee the relative positioning of removed elements, // we force transition-group to update its children into two passes: // in the first pass, we remove all nodes that need to be removed, // triggering their leaving transition; in the second pass, we insert/move // into the final disired state. This way in the second pass removed // nodes will remain where they should be. var props = extend({ tag: String, moveClass: String }, transitionProps); delete props.mode; var TransitionGroup = { props: props, render: function render (h) { var tag = this.tag || this.$vnode.data.tag || 'span'; var map = Object.create(null); var prevChildren = this.prevChildren = this.children; var rawChildren = this.$slots.default || []; var children = this.children = []; var transitionData = extractTransitionData(this); for (var i = 0; i < rawChildren.length; i++) { var c = rawChildren[i]; if (c.tag) { if (c.key != null && String(c.key).indexOf('__vlist') !== 0) { children.push(c); map[c.key] = c ;(c.data || (c.data = {})).transition = transitionData; } else if (process.env.NODE_ENV !== 'production') { var opts = c.componentOptions; var name = opts ? (opts.Ctor.options.name || opts.tag) : c.tag; warn(("<transition-group> children must be keyed: <" + name + ">")); } } } if (prevChildren) { var kept = []; var removed = []; for (var i$1 = 0; i$1 < prevChildren.length; i$1++) { var c$1 = prevChildren[i$1]; c$1.data.transition = transitionData; c$1.data.pos = c$1.elm.getBoundingClientRect(); if (map[c$1.key]) { kept.push(c$1); } else { removed.push(c$1); } } this.kept = h(tag, null, kept); this.removed = removed; } return h(tag, null, children) }, beforeUpdate: function beforeUpdate () { // force removing pass this.__patch__( this._vnode, this.kept, false, // hydrating true // removeOnly (!important, avoids unnecessary moves) ); this._vnode = this.kept; }, updated: function updated () { var children = this.prevChildren; var moveClass = this.moveClass || ((this.name || 'v') + '-move'); if (!children.length || !this.hasMove(children[0].elm, moveClass)) { return } // we divide the work into three loops to avoid mixing DOM reads and writes // in each iteration - which helps prevent layout thrashing. children.forEach(callPendingCbs); children.forEach(recordPosition); children.forEach(applyTranslation); // force reflow to put everything in position var f = document.body.offsetHeight; // eslint-disable-line children.forEach(function (c) { if (c.data.moved) { var el = c.elm; var s = el.style; addTransitionClass(el, moveClass); s.transform = s.WebkitTransform = s.transitionDuration = ''; el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) { if (!e || /transform$/.test(e.propertyName)) { el.removeEventListener(transitionEndEvent, cb); el._moveCb = null; removeTransitionClass(el, moveClass); } }); } }); }, methods: { hasMove: function hasMove (el, moveClass) { /* istanbul ignore if */ if (!hasTransition) { return false } if (this._hasMove != null) { return this._hasMove } addTransitionClass(el, moveClass); var info = getTransitionInfo(el); removeTransitionClass(el, moveClass); return (this._hasMove = info.hasTransform) } } }; function callPendingCbs (c) { /* istanbul ignore if */ if (c.elm._moveCb) { c.elm._moveCb(); } /* istanbul ignore if */ if (c.elm._enterCb) { c.elm._enterCb(); } } function recordPosition (c) { c.data.newPos = c.elm.getBoundingClientRect(); } function applyTranslation (c) { var oldPos = c.data.pos; var newPos = c.data.newPos; var dx = oldPos.left - newPos.left; var dy = oldPos.top - newPos.top; if (dx || dy) { c.data.moved = true; var s = c.elm.style; s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)"; s.transitionDuration = '0s'; } } var platformComponents = { Transition: Transition, TransitionGroup: TransitionGroup }; /* */ // install platform specific utils Vue$2.config.isUnknownElement = isUnknownElement; Vue$2.config.isReservedTag = isReservedTag; Vue$2.config.getTagNamespace = getTagNamespace; Vue$2.config.mustUseProp = mustUseProp; // install platform runtime directives & components extend(Vue$2.options.directives, platformDirectives); extend(Vue$2.options.components, platformComponents); // install platform patch function Vue$2.prototype.__patch__ = inBrowser ? patch$1 : noop; // wrap mount Vue$2.prototype.$mount = function ( el, hydrating ) { el = el && inBrowser ? query(el) : undefined; return this._mount(el, hydrating) }; // devtools global hook /* istanbul ignore next */ setTimeout(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue$2); } else if ( process.env.NODE_ENV !== 'production' && inBrowser && !isEdge && /Chrome\/\d+/.test(window.navigator.userAgent) ) { console.log( 'Download the Vue Devtools for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools' ); } } }, 0); module.exports = Vue$2; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8), (function() { return this; }()))) /***/ }, /* 8 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-avatar", class: [_vm.themeClass] }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-1cbfca0d", module.exports) } } /***/ }, /* 10 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-avatar.md-primary.md-avatar-icon {\n background-color: PRIMARY-COLOR; }\n .THEME_NAME.md-avatar.md-primary.md-avatar-icon .md-icon {\n color: PRIMARY-CONTRAST-0.99999; }\n\n.THEME_NAME.md-avatar.md-accent.md-avatar-icon {\n background-color: ACCENT-COLOR; }\n .THEME_NAME.md-avatar.md-accent.md-avatar-icon .md-icon {\n color: ACCENT-CONTRAST-0.99999; }\n\n.THEME_NAME.md-avatar.md-warn.md-avatar-icon {\n background-color: WARN-COLOR; }\n .THEME_NAME.md-avatar.md-warn.md-avatar-icon .md-icon {\n color: WARN-CONTRAST-0.99999; }\n" /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdBackdrop = __webpack_require__(12); var _mdBackdrop2 = _interopRequireDefault(_mdBackdrop); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-backdrop', Vue.extend(_mdBackdrop2.default)); } module.exports = exports['default']; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(13) /* script */ __vue_exports__ = __webpack_require__(14) /* template */ var __vue_template__ = __webpack_require__(15) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdBackdrop/mdBackdrop.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-df1259a6", __vue_options__) } else { hotAPI.reload("data-v-df1259a6", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdBackdrop.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 13 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 14 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // exports.default = { methods: { close: function close() { this.$emit('close'); } } }; module.exports = exports['default']; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-backdrop", on: { "click": _vm.close, "keyup": function($event) { if (_vm._k($event.keyCode, "esc", 27)) { return; } _vm.close($event) } } }) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-df1259a6", module.exports) } } /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdBottomBar = __webpack_require__(17); var _mdBottomBar2 = _interopRequireDefault(_mdBottomBar); var _mdBottomBarItem = __webpack_require__(21); var _mdBottomBarItem2 = _interopRequireDefault(_mdBottomBarItem); var _mdBottomBar3 = __webpack_require__(24); var _mdBottomBar4 = _interopRequireDefault(_mdBottomBar3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-bottom-bar', Vue.extend(_mdBottomBar2.default)); Vue.component('md-bottom-bar-item', Vue.extend(_mdBottomBarItem2.default)); Vue.material.styles.push(_mdBottomBar4.default); } module.exports = exports['default']; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(18) /* script */ __vue_exports__ = __webpack_require__(19) /* template */ var __vue_template__ = __webpack_require__(20) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdBottomBar/mdBottomBar.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-039c211e", __vue_options__) } else { hotAPI.reload("data-v-039c211e", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdBottomBar.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 18 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { props: { mdShift: Boolean }, mixins: [_mixin2.default], computed: { classes: function classes() { return this.mdShift ? 'md-shift' : 'md-fixed'; } } }; // // // // // // // // module.exports = exports['default']; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-bottom-bar", class: [_vm.themeClass, _vm.classes] }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-039c211e", module.exports) } } /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(22) /* template */ var __vue_template__ = __webpack_require__(23) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdBottomBar/mdBottomBarItem.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-1c07f8a4", __vue_options__) } else { hotAPI.reload("data-v-1c07f8a4", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdBottomBarItem.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 22 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // // // // // // // // // // // // // exports.default = { props: { mdIcon: String, mdActive: Boolean, href: String }, data: function data() { return { active: false }; }, computed: { classes: function classes() { return { 'md-active': this.active }; } }, watch: { mdActive: function mdActive(active) { this.setActive(active); } }, methods: { setActive: function setActive(active) { this.$parent.$children.forEach(function (item) { item.active = false; }); this.active = !!active; } }, mounted: function mounted() { if (!this.$parent.$el.classList.contains('md-bottom-bar')) { this.$destroy(); throw new Error('You should wrap the md-bottom-bar-item in a md-bottom-bar'); } if (this.mdActive) { this.active = true; } } }; module.exports = exports['default']; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return (_vm.href) ? _c('a', { directives: [{ name: "md-ink-ripple", rawName: "v-md-ink-ripple" }], staticClass: "md-bottom-bar-item", class: _vm.classes, attrs: { "href": _vm.href }, on: { "click": _vm.setActive } }, [_c('md-icon', [_vm._v(_vm._s(_vm.mdIcon))]), _vm._v(" "), _c('span', { staticClass: "md-text" }, [_vm._t("default")], true)]) : _c('button', { directives: [{ name: "md-ink-ripple", rawName: "v-md-ink-ripple" }], staticClass: "md-bottom-bar-item", class: _vm.classes, attrs: { "type": "button" }, on: { "click": _vm.setActive } }, [_c('md-icon', [_vm._v(_vm._s(_vm.mdIcon))]), _vm._v(" "), _c('span', { staticClass: "md-text" }, [_vm._t("default")], true)]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-1c07f8a4", module.exports) } } /***/ }, /* 24 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-bottom-bar.md-fixed {\n background-color: BACKGROUND-COLOR; }\n .THEME_NAME.md-bottom-bar.md-fixed .md-bottom-bar-item {\n color: BACKGROUND-CONTRAST-0.54; }\n .THEME_NAME.md-bottom-bar.md-fixed .md-bottom-bar-item:hover:not(.md-active) {\n color: BACKGROUND-CONTRAST-0.87; }\n .THEME_NAME.md-bottom-bar.md-fixed .md-bottom-bar-item.md-active {\n color: PRIMARY-COLOR; }\n .THEME_NAME.md-bottom-bar.md-fixed.md-accent .md-bottom-bar-item.md-active {\n color: ACCENT-COLOR; }\n .THEME_NAME.md-bottom-bar.md-fixed.md-warn .md-bottom-bar-item.md-active {\n color: WARN-COLOR; }\n .THEME_NAME.md-bottom-bar.md-fixed.md-transparent .md-bottom-bar-item.md-active {\n color: BACKGROUND-CONTRAST; }\n\n.THEME_NAME.md-bottom-bar.md-shift {\n background-color: PRIMARY-COLOR;\n color: PRIMARY-CONTRAST; }\n .THEME_NAME.md-bottom-bar.md-shift .md-bottom-bar-item {\n color: PRIMARY-CONTRAST-0.54; }\n .THEME_NAME.md-bottom-bar.md-shift .md-bottom-bar-item:hover:not(.md-active) {\n color: PRIMARY-CONTRAST-0.87; }\n .THEME_NAME.md-bottom-bar.md-shift .md-bottom-bar-item.md-active {\n color: PRIMARY-CONTRAST; }\n .THEME_NAME.md-bottom-bar.md-shift.md-accent {\n background-color: ACCENT-COLOR; }\n .THEME_NAME.md-bottom-bar.md-shift.md-accent .md-bottom-bar-item {\n color: ACCENT-CONTRAST-0.54; }\n .THEME_NAME.md-bottom-bar.md-shift.md-accent .md-bottom-bar-item:hover:not(.md-active) {\n color: ACCENT-CONTRAST-0.87; }\n .THEME_NAME.md-bottom-bar.md-shift.md-accent .md-bottom-bar-item.md-active {\n color: ACCENT-CONTRAST; }\n .THEME_NAME.md-bottom-bar.md-shift.md-warn {\n background-color: WARN-COLOR; }\n .THEME_NAME.md-bottom-bar.md-shift.md-warn .md-bottom-bar-item {\n color: WARN-CONTRAST-0.54; }\n .THEME_NAME.md-bottom-bar.md-shift.md-warn .md-bottom-bar-item:hover:not(.md-active) {\n color: WARN-CONTRAST-0.87; }\n .THEME_NAME.md-bottom-bar.md-shift.md-warn .md-bottom-bar-item.md-active {\n color: WARN-CONTRAST; }\n .THEME_NAME.md-bottom-bar.md-shift.md-transparent {\n background-color: transparent; }\n .THEME_NAME.md-bottom-bar.md-shift.md-transparent .md-bottom-bar-item {\n color: BACKGROUND-CONTRAST-0.54; }\n .THEME_NAME.md-bottom-bar.md-shift.md-transparent .md-bottom-bar-item:hover:not(.md-active) {\n color: BACKGROUND-CONTRAST-0.87; }\n .THEME_NAME.md-bottom-bar.md-shift.md-transparent .md-bottom-bar-item.md-active {\n color: BACKGROUND-CONTRAST; }\n" /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdButton = __webpack_require__(26); var _mdButton2 = _interopRequireDefault(_mdButton); var _mdButton3 = __webpack_require__(30); var _mdButton4 = _interopRequireDefault(_mdButton3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-button', Vue.extend(_mdButton2.default)); Vue.material.styles.push(_mdButton4.default); } module.exports = exports['default']; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(27) /* script */ __vue_exports__ = __webpack_require__(28) /* template */ var __vue_template__ = __webpack_require__(29) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdButton/mdButton.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-9b3983a6", __vue_options__) } else { hotAPI.reload("data-v-9b3983a6", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdButton.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 27 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { props: { href: String, target: String, rel: String, type: { type: String, default: 'button' }, disabled: Boolean }, mixins: [_mixin2.default], computed: { newRel: function newRel() { if (this.target === '_blank') { return this.rel || 'noopener'; } return this.rel; } } }; // // // // // // // // // // // // // // module.exports = exports['default']; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return (!_vm.href) ? _c('button', { staticClass: "md-button", class: [_vm.themeClass], attrs: { "type": _vm.type, "disabled": _vm.disabled }, on: { "click": function($event) { _vm.$emit('click', $event) } } }, [_c('md-ink-ripple', { attrs: { "md-disabled": _vm.disabled } }), _vm._v(" "), _vm._t("default")], true) : _c('a', { staticClass: "md-button", class: [_vm.themeClass], attrs: { "href": _vm.href, "disabled": _vm.disabled, "target": _vm.target, "rel": _vm.newRel }, on: { "click": function($event) { _vm.$emit('click', $event) } } }, [_c('md-ink-ripple', { attrs: { "md-disabled": _vm.disabled } }), _vm._v(" "), _vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-9b3983a6", module.exports) } } /***/ }, /* 30 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-button:not([disabled]).md-raised:not(.md-icon-button) {\n color: BACKGROUND-COLOR-900;\n background-color: BACKGROUND-COLOR-50; }\n .THEME_NAME.md-button:not([disabled]).md-raised:not(.md-icon-button):hover {\n background-color: BACKGROUND-COLOR-200; }\n\n.THEME_NAME.md-button:not([disabled]).md-raised.md-icon-button:not(.md-raised) {\n color: BACKGROUND-COLOR; }\n\n.THEME_NAME.md-button:not([disabled]).md-fab {\n color: ACCENT-CONTRAST;\n background-color: ACCENT-COLOR; }\n .THEME_NAME.md-button:not([disabled]).md-fab:hover {\n background-color: ACCENT-COLOR-600; }\n .THEME_NAME.md-button:not([disabled]).md-fab.md-clean {\n color: BACKGROUND-COLOR-900;\n background-color: BACKGROUND-COLOR-50; }\n .THEME_NAME.md-button:not([disabled]).md-fab.md-clean:hover {\n background-color: BACKGROUND-COLOR-200; }\n\n.THEME_NAME.md-button:not([disabled]).md-primary:not(.md-icon-button) {\n color: PRIMARY-COLOR; }\n\n.THEME_NAME.md-button:not([disabled]).md-primary.md-raised, .THEME_NAME.md-button:not([disabled]).md-primary.md-fab {\n background-color: PRIMARY-COLOR;\n color: PRIMARY-CONTRAST; }\n .THEME_NAME.md-button:not([disabled]).md-primary.md-raised:hover, .THEME_NAME.md-button:not([disabled]).md-primary.md-fab:hover {\n background-color: PRIMARY-COLOR-600; }\n\n.THEME_NAME.md-button:not([disabled]).md-primary.md-icon-button:not(.md-raised) {\n color: PRIMARY-COLOR; }\n\n.THEME_NAME.md-button:not([disabled]).md-accent:not(.md-icon-button) {\n color: ACCENT-COLOR; }\n\n.THEME_NAME.md-button:not([disabled]).md-accent.md-raised {\n background-color: ACCENT-COLOR;\n color: ACCENT-CONTRAST; }\n .THEME_NAME.md-button:not([disabled]).md-accent.md-raised:hover {\n background-color: ACCENT-COLOR-600; }\n\n.THEME_NAME.md-button:not([disabled]).md-accent.md-icon-button:not(.md-raised) {\n color: ACCENT-COLOR; }\n\n.THEME_NAME.md-button:not([disabled]).md-warn:not(.md-icon-button) {\n color: WARN-COLOR; }\n\n.THEME_NAME.md-button:not([disabled]).md-warn.md-raised, .THEME_NAME.md-button:not([disabled]).md-warn.md-fab {\n background-color: WARN-COLOR;\n color: WARN-CONTRAST; }\n .THEME_NAME.md-button:not([disabled]).md-warn.md-raised:hover, .THEME_NAME.md-button:not([disabled]).md-warn.md-fab:hover {\n background-color: WARN-COLOR-600; }\n\n.THEME_NAME.md-button:not([disabled]).md-warn.md-icon-button:not(.md-raised) {\n color: WARN-COLOR; }\n" /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdButtonToggle = __webpack_require__(32); var _mdButtonToggle2 = _interopRequireDefault(_mdButtonToggle); var _mdButtonToggle3 = __webpack_require__(36); var _mdButtonToggle4 = _interopRequireDefault(_mdButtonToggle3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-button-toggle', Vue.extend(_mdButtonToggle2.default)); Vue.material.styles.push(_mdButtonToggle4.default); } module.exports = exports['default']; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(33) /* script */ __vue_exports__ = __webpack_require__(34) /* template */ var __vue_template__ = __webpack_require__(35) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdButtonToggle/mdButtonToggle.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-106cf22d", __vue_options__) } else { hotAPI.reload("data-v-106cf22d", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdButtonToggle.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 33 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var onClickButton = void 0; // // // // // // // // exports.default = { props: { mdSingle: Boolean }, mixins: [_mixin2.default], mounted: function mounted() { var _this = this; this.$children.forEach(function (child) { var element = child.$el; var toggleClass = 'md-toggle'; onClickButton = function onClickButton() { if (_this.mdSingle) { _this.$children.forEach(function (child) { child.$el.classList.remove(toggleClass); }); element.classList.add(toggleClass); } else { element.classList.toggle(toggleClass); } }; if (element && element.classList.contains('md-button')) { element.addEventListener('click', onClickButton); } }); }, beforeDestroy: function beforeDestroy() { this.$children.forEach(function (child) { var element = child.$el; if (element && element.classList.contains('md-button')) { element.removeEventListener('click', onClickButton); } }); } }; module.exports = exports['default']; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-button-toggle", class: [_vm.themeClass] }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-106cf22d", module.exports) } } /***/ }, /* 36 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-button-toggle .md-button:after {\n width: 1px;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n content: \" \"; }\n\n.THEME_NAME.md-button-toggle .md-toggle {\n color: BACKGROUND-CONTRAST-600;\n background-color: BACKGROUND-COLOR-500; }\n .THEME_NAME.md-button-toggle .md-toggle:hover:not([disabled]) {\n background-color: BACKGROUND-COLOR-600; }\n .THEME_NAME.md-button-toggle .md-toggle + .md-toggle:after {\n background-color: BACKGROUND-COLOR-600; }\n\n.THEME_NAME.md-button-toggle.md-primary .md-toggle {\n color: PRIMARY-CONTRAST;\n background-color: PRIMARY-COLOR; }\n .THEME_NAME.md-button-toggle.md-primary .md-toggle:hover:not([disabled]) {\n background-color: PRIMARY-COLOR-600; }\n .THEME_NAME.md-button-toggle.md-primary .md-toggle + .md-toggle:after {\n background-color: PRIMARY-COLOR-700; }\n\n.THEME_NAME.md-button-toggle.md-accent .md-toggle {\n color: ACCENT-CONTRAST;\n background-color: ACCENT-COLOR; }\n .THEME_NAME.md-button-toggle.md-accent .md-toggle:hover:not([disabled]) {\n background-color: ACCENT-COLOR-600; }\n .THEME_NAME.md-button-toggle.md-accent .md-toggle + .md-toggle:after {\n background-color: ACCENT-COLOR-700; }\n\n.THEME_NAME.md-button-toggle.md-warn .md-toggle {\n color: WARN-CONTRAST;\n background-color: WARN-COLOR; }\n .THEME_NAME.md-button-toggle.md-warn .md-toggle:hover:not([disabled]) {\n background-color: WARN-COLOR-600; }\n .THEME_NAME.md-button-toggle.md-warn .md-toggle + .md-toggle:after {\n background-color: WARN-COLOR-700; }\n\n.THEME_NAME.md-button-toggle [disabled] {\n color: rgba(0, 0, 0, 0.26); }\n .THEME_NAME.md-button-toggle [disabled].md-toggle {\n color: BACKGROUND-CONTRAST-0.2;\n background-color: rgba(0, 0, 0, 0.26); }\n" /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdCard = __webpack_require__(38); var _mdCard2 = _interopRequireDefault(_mdCard); var _mdCardMedia = __webpack_require__(42); var _mdCardMedia2 = _interopRequireDefault(_mdCardMedia); var _mdCardMediaCover = __webpack_require__(45); var _mdCardMediaCover2 = _interopRequireDefault(_mdCardMediaCover); var _mdCardMediaActions = __webpack_require__(48); var _mdCardMediaActions2 = _interopRequireDefault(_mdCardMediaActions); var _mdCardHeader = __webpack_require__(50); var _mdCardHeader2 = _interopRequireDefault(_mdCardHeader); var _mdCardHeaderText = __webpack_require__(52); var _mdCardHeaderText2 = _interopRequireDefault(_mdCardHeaderText); var _mdCardContent = __webpack_require__(55); var _mdCardContent2 = _interopRequireDefault(_mdCardContent); var _mdCardActions = __webpack_require__(57); var _mdCardActions2 = _interopRequireDefault(_mdCardActions); var _mdCardArea = __webpack_require__(59); var _mdCardArea2 = _interopRequireDefault(_mdCardArea); var _mdCardExpand = __webpack_require__(62); var _mdCardExpand2 = _interopRequireDefault(_mdCardExpand); var _mdCard3 = __webpack_require__(65); var _mdCard4 = _interopRequireDefault(_mdCard3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-card', Vue.extend(_mdCard2.default)); Vue.component('md-card-media', Vue.extend(_mdCardMedia2.default)); Vue.component('md-card-media-cover', Vue.extend(_mdCardMediaCover2.default)); Vue.component('md-card-media-actions', Vue.extend(_mdCardMediaActions2.default)); Vue.component('md-card-header', Vue.extend(_mdCardHeader2.default)); Vue.component('md-card-header-text', Vue.extend(_mdCardHeaderText2.default)); Vue.component('md-card-content', Vue.extend(_mdCardContent2.default)); Vue.component('md-card-actions', Vue.extend(_mdCardActions2.default)); Vue.component('md-card-area', Vue.extend(_mdCardArea2.default)); Vue.component('md-card-expand', Vue.extend(_mdCardExpand2.default)); Vue.material.styles.push(_mdCard4.default); } module.exports = exports['default']; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(39) /* script */ __vue_exports__ = __webpack_require__(40) /* template */ var __vue_template__ = __webpack_require__(41) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdCard/mdCard.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-5074f4ed", __vue_options__) } else { hotAPI.reload("data-v-5074f4ed", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdCard.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 39 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { props: { mdWithHover: Boolean }, mixins: [_mixin2.default], computed: { classes: function classes() { return { 'md-with-hover': this.mdWithHover }; } } }; // // // // // // // // module.exports = exports['default']; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-card", class: [_vm.themeClass, _vm.classes] }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-5074f4ed", module.exports) } } /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(43) /* template */ var __vue_template__ = __webpack_require__(44) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdCard/mdCardMedia.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-623c9b27", __vue_options__) } else { hotAPI.reload("data-v-623c9b27", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdCardMedia.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 43 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // exports.default = { props: { mdRatio: String, mdMedium: Boolean, mdBig: Boolean }, computed: { classes: function classes() { var classes = { 'md-16-9': this.mdRatio === '16:9' || this.mdRatio === '16/9', 'md-4-3': this.mdRatio === '4:3' || this.mdRatio === '4/3', 'md-1-1': this.mdRatio === '1:1' || this.mdRatio === '1/1' }; if (this.mdMedium || this.mdBig) { classes = { 'md-medium': this.mdMedium, 'md-big': this.mdBig }; } return classes; } } }; module.exports = exports['default']; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-card-media", class: _vm.classes }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-623c9b27", module.exports) } } /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(46) /* template */ var __vue_template__ = __webpack_require__(47) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdCard/mdCardMediaCover.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-1a9ce900", __vue_options__) } else { hotAPI.reload("data-v-1a9ce900", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdCardMediaCover.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 46 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // // var getImageAlpha = function getImageAlpha(image, onLoad) { var canvas = document.createElement('canvas'); image.onload = function () { var colorSum = 0; var ctx = void 0; var imageData = void 0; var imageMetadata = void 0; var r = void 0; var g = void 0; var b = void 0; var average = void 0; canvas.width = this.width; canvas.height = this.height; ctx = canvas.getContext('2d'); ctx.drawImage(this, 0, 0); imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); imageMetadata = imageData.data; for (var x = 0, len = imageMetadata.length; x < len; x += 4) { r = imageMetadata[x]; g = imageMetadata[x + 1]; b = imageMetadata[x + 2]; average = Math.floor((r + g + b) / 3); colorSum += average; } onLoad(Math.floor(colorSum / (this.width * this.height))); }; }; exports.default = { props: { mdTextScrim: Boolean, mdSolid: Boolean }, data: function data() { return { backdropBg: {} }; }, computed: { classes: function classes() { return { 'md-text-scrim': this.mdTextScrim, 'md-solid': this.mdSolid }; }, styles: function styles() { return { background: this.backdropBg }; } }, methods: { applyScrimColor: function applyScrimColor(darkness) { if (this.$refs.backdrop) { this.backdropBg = 'linear-gradient(to bottom, rgba(0, 0, 0, 0) 20%, rgba(0, 0, 0, ' + darkness / 2 + ') 66%, rgba(0, 0, 0, ' + darkness + ') 100%)'; } }, applySolidColor: function applySolidColor(darkness) { var area = this.$el.querySelector('.md-card-area'); if (area) { area.style.background = 'rgba(0, 0, 0, ' + darkness + ')'; } } }, mounted: function mounted() { var _this = this; var image = this.$el.querySelector('img'); if (image && (this.mdTextScrim || this.mdSolid)) { getImageAlpha(image, function (lightness) { var limit = 256; var darkness = (Math.abs(limit - lightness) * 100 / limit + 15) / 100; if (darkness >= 0.7) { darkness = 0.7; } if (_this.mdTextScrim) { _this.applyScrimColor(darkness); } else if (_this.mdSolid) { _this.applySolidColor(darkness); } }); } } }; module.exports = exports['default']; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-card-media-cover", class: _vm.classes }, [_vm._t("default"), _vm._v(" "), (_vm.mdTextScrim) ? _c('div', { ref: "backdrop", staticClass: "md-card-backdrop", style: (_vm.styles) }) : _vm._e()], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-1a9ce900", module.exports) } } /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* template */ var __vue_template__ = __webpack_require__(49) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdCard/mdCardMediaActions.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-9711f4f4", __vue_options__) } else { hotAPI.reload("data-v-9711f4f4", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdCardMediaActions.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-card-media-actions" }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-9711f4f4", module.exports) } } /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* template */ var __vue_template__ = __webpack_require__(51) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdCard/mdCardHeader.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-2b945d4c", __vue_options__) } else { hotAPI.reload("data-v-2b945d4c", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdCardHeader.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-card-header" }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-2b945d4c", module.exports) } } /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(53) /* template */ var __vue_template__ = __webpack_require__(54) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdCard/mdCardHeaderText.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-3c04eb27", __vue_options__) } else { hotAPI.reload("data-v-3c04eb27", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdCardHeaderText.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 53 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // exports.default = { mounted: function mounted() { this.parentClasses = this.$parent.$el.classList; if (this.parentClasses.contains('md-card-header')) { this.insideParent = true; this.parentClasses.add('md-card-header-flex'); } }, destroyed: function destroyed() { this.parentClasses.remove('md-card-header-flex'); } }; module.exports = exports['default']; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-card-header-text" }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-3c04eb27", module.exports) } } /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* template */ var __vue_template__ = __webpack_require__(56) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdCard/mdCardContent.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-015e0e7c", __vue_options__) } else { hotAPI.reload("data-v-015e0e7c", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdCardContent.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-card-content" }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-015e0e7c", module.exports) } } /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* template */ var __vue_template__ = __webpack_require__(58) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdCard/mdCardActions.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-78014100", __vue_options__) } else { hotAPI.reload("data-v-78014100", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdCardActions.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-card-actions" }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-78014100", module.exports) } } /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(60) /* template */ var __vue_template__ = __webpack_require__(61) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdCard/mdCardArea.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-3894e89a", __vue_options__) } else { hotAPI.reload("data-v-3894e89a", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdCardArea.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 60 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // exports.default = { props: { mdInset: Boolean }, computed: { classes: function classes() { return { 'md-inset': this.mdInset }; } } }; module.exports = exports['default']; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-card-area", class: _vm.classes }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-3894e89a", module.exports) } } /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(63) /* template */ var __vue_template__ = __webpack_require__(64) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdCard/mdCardExpand.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-d6fa0232", __vue_options__) } else { hotAPI.reload("data-v-d6fa0232", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdCardExpand.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 63 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // exports.default = { methods: { setContentMargin: function setContentMargin() { this.content.style.marginTop = -this.content.offsetHeight + 'px'; }, toggle: function toggle() { this.$refs.expand.classList.toggle('md-active'); }, onWindowResize: function onWindowResize() { window.requestAnimationFrame(this.setContentMargin); } }, mounted: function mounted() { this.trigger = this.$el.querySelector('[md-expand-trigger]'); this.content = this.$el.querySelector('.md-card-content'); if (this.content) { this.setContentMargin(); this.trigger.addEventListener('click', this.toggle); window.addEventListener('resize', this.onWindowResize); } }, destroyed: function destroyed() { if (this.content) { this.trigger.removeEventListener('click', this.toggle); window.removeEventListener('resize', this.onWindowResize); } } }; module.exports = exports['default']; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { ref: "expand", staticClass: "md-card-expand" }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-d6fa0232", module.exports) } } /***/ }, /* 65 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-card {\n background-color: BACKGROUND-COLOR-A100; }\n .THEME_NAME.md-card.md-primary {\n background-color: PRIMARY-COLOR;\n color: PRIMARY-CONTRAST; }\n .THEME_NAME.md-card.md-primary .md-card-header .md-icon-button .md-icon,\n .THEME_NAME.md-card.md-primary .md-card-actions .md-icon-button .md-icon {\n color: PRIMARY-CONTRAST-0.87; }\n .THEME_NAME.md-card.md-accent {\n background-color: ACCENT-COLOR;\n color: ACCENT-CONTRAST; }\n .THEME_NAME.md-card.md-accent .md-card-header .md-icon-button .md-icon,\n .THEME_NAME.md-card.md-accent .md-card-actions .md-icon-button .md-icon {\n color: ACCENT-CONTRAST-0.87; }\n .THEME_NAME.md-card.md-warn {\n background-color: WARN-COLOR;\n color: WARN-CONTRAST; }\n .THEME_NAME.md-card.md-warn .md-card-header .md-icon-button .md-icon,\n .THEME_NAME.md-card.md-warn .md-card-actions .md-icon-button .md-icon {\n color: WARN-CONTRAST-0.87; }\n .THEME_NAME.md-card .md-card-header .md-icon-button .md-icon,\n .THEME_NAME.md-card .md-card-actions .md-icon-button .md-icon {\n color: BACKGROUND-CONTRAST-0.54; }\n .THEME_NAME.md-card > .md-card-area:after {\n background-color: BACKGROUND-CONTRAST-0.12; }\n .THEME_NAME.md-card .md-card-media-cover.md-text-scrim .md-backdrop {\n background: linear-gradient(to bottom, BACKGROUND-CONTRAST-0.0 20%, BACKGROUND-CONTRAST-0.275 66%, BACKGROUND-CONTRAST-0.55 100%); }\n .THEME_NAME.md-card .md-card-media-cover.md-solid .md-card-area {\n background-color: BACKGROUND-CONTRAST-0.4; }\n .THEME_NAME.md-card .md-card-expand .md-card-actions {\n background-color: BACKGROUND-COLOR-A100; }\n" /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdCheckbox = __webpack_require__(67); var _mdCheckbox2 = _interopRequireDefault(_mdCheckbox); var _mdCheckbox3 = __webpack_require__(71); var _mdCheckbox4 = _interopRequireDefault(_mdCheckbox3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-checkbox', Vue.extend(_mdCheckbox2.default)); Vue.material.styles.push(_mdCheckbox4.default); } module.exports = exports['default']; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(68) /* script */ __vue_exports__ = __webpack_require__(69) /* template */ var __vue_template__ = __webpack_require__(70) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdCheckbox/mdCheckbox.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-9db725e6", __vue_options__) } else { hotAPI.reload("data-v-9db725e6", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdCheckbox.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 68 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { props: { name: String, value: [String, Boolean], id: String, disabled: Boolean }, mixins: [_mixin2.default], data: function data() { return { checked: this.value }; }, computed: { classes: function classes() { return { 'md-checked': Boolean(this.checked), 'md-disabled': this.disabled }; } }, watch: { value: function value() { this.checked = this.value; } }, methods: { toggleCheck: function toggleCheck($event) { if (!this.disabled) { this.checked = !this.checked; this.$emit('change', this.checked, $event); this.$emit('input', this.checked, $event); } } } }; // // // // // // // // // // // // // // module.exports = exports['default']; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-checkbox", class: [_vm.themeClass, _vm.classes] }, [_c('div', { directives: [{ name: "md-ink-ripple", rawName: "v-md-ink-ripple", value: (_vm.disabled), expression: "disabled" }], staticClass: "md-checkbox-container", attrs: { "tabindex": "0" }, on: { "click": function($event) { $event.stopPropagation(); _vm.toggleCheck($event) } } }, [_c('input', { attrs: { "type": "checkbox", "name": _vm.name, "id": _vm.id, "disabled": _vm.disabled, "tabindex": "-1" }, domProps: { "value": _vm.value } })]), _vm._v(" "), (_vm.$slots.default) ? _c('label', { staticClass: "md-checkbox-label", attrs: { "for": _vm.id || _vm.name } }, [_vm._t("default")], true) : _vm._e()]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-9db725e6", module.exports) } } /***/ }, /* 71 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-checkbox.md-checked .md-checkbox-container {\n background-color: ACCENT-COLOR;\n border-color: ACCENT-COLOR; }\n .THEME_NAME.md-checkbox.md-checked .md-checkbox-container:after {\n border-color: ACCENT-CONTRAST; }\n\n.THEME_NAME.md-checkbox.md-checked .md-ink-ripple {\n color: ACCENT-COLOR; }\n\n.THEME_NAME.md-checkbox.md-checked .md-ripple {\n opacity: .38; }\n\n.THEME_NAME.md-checkbox.md-primary.md-checked .md-checkbox-container {\n background-color: PRIMARY-COLOR;\n border-color: PRIMARY-COLOR; }\n .THEME_NAME.md-checkbox.md-primary.md-checked .md-checkbox-container:after {\n border-color: PRIMARY-CONTRAST; }\n\n.THEME_NAME.md-checkbox.md-primary.md-checked .md-ink-ripple {\n color: PRIMARY-COLOR; }\n\n.THEME_NAME.md-checkbox.md-warn.md-checked .md-checkbox-container {\n background-color: WARN-COLOR;\n border-color: WARN-COLOR; }\n .THEME_NAME.md-checkbox.md-warn.md-checked .md-checkbox-container:after {\n border-color: WARN-CONTRAST; }\n\n.THEME_NAME.md-checkbox.md-warn.md-checked .md-ink-ripple {\n color: WARN-COLOR; }\n\n.THEME_NAME.md-checkbox.md-disabled.md-checked .md-checkbox-container {\n background-color: rgba(0, 0, 0, 0.26);\n border-color: transparent; }\n\n.THEME_NAME.md-checkbox.md-disabled:not(.md-checked) .md-checkbox-container {\n border-color: rgba(0, 0, 0, 0.26); }\n" /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdTheme = __webpack_require__(73); var _mdTheme2 = _interopRequireDefault(_mdTheme); var _mdInkRipple = __webpack_require__(78); var _mdInkRipple2 = _interopRequireDefault(_mdInkRipple); var _core = __webpack_require__(82); var _core2 = _interopRequireDefault(_core); __webpack_require__(83); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* Code Components */ function install(Vue) { if (install.installed) { console.warn('Vue Material is already installed.'); return; } install.installed = true; Vue.use(_mdTheme2.default); Vue.use(_mdInkRipple2.default); Vue.material.styles.push(_core2.default); } /* Core Stylesheets */ module.exports = exports['default']; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _palette = __webpack_require__(74); var _palette2 = _interopRequireDefault(_palette); var _rgba = __webpack_require__(75); var _rgba2 = _interopRequireDefault(_rgba); var _MdTheme = __webpack_require__(76); var _MdTheme2 = _interopRequireDefault(_MdTheme); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var VALID_THEME_TYPE = ['primary', 'accent', 'background', 'warn', 'hue-1', 'hue-2', 'hue-3']; var DEFAULT_THEME_COLORS = { primary: 'indigo', accent: 'pink', background: 'grey', warn: 'deep-orange' }; /*const DEFAULT_HUES = { accent: { 'hue-1': 'A100', 'hue-2': 'A400', 'hue-3': 'A700' }, background: { 'hue-1': 'A100', 'hue-2': '100', 'hue-3': '300' } };*/ var createNewStyleElement = function createNewStyleElement(style, name) { var head = document.head; var styleId = 'md-theme-' + name; var styleElement = head.querySelector('#' + styleId); if (!styleElement) { var newTag = document.createElement('style'); style = style.replace(/THEME_NAME/g, styleId); newTag.type = 'text/css'; newTag.id = styleId; newTag.textContent = style; head.appendChild(newTag); } else { styleElement.textContent = style; } }; var registeredThemes = []; var parseStyle = function parseStyle(style, theme) { VALID_THEME_TYPE.forEach(function (type) { style = style.replace(RegExp('(' + type.toUpperCase() + ')-(COLOR|CONTRAST)-?(A?\\d*)-?(\\d*\\.?\\d+)?', 'g'), function (match, paletteType, colorType, hue, opacity) { var color = void 0; var colorVariant = +hue === 0 ? 500 : hue; if (theme[type]) { if (typeof theme[type] === 'string') { color = _palette2.default[theme[type]]; } else { color = _palette2.default[theme[type].color] || _palette2.default[DEFAULT_THEME_COLORS[type]]; colorVariant = +hue === 0 ? theme[type].hue : hue; } } else { color = _palette2.default[DEFAULT_THEME_COLORS[type]]; } if (colorType === 'COLOR') { var isDefault = _palette2.default[theme[type]]; if (!hue && !isDefault) { if (type === 'accent') { colorVariant = 'A200'; } else if (type === 'background') { colorVariant = 50; } } if (opacity) { return (0, _rgba2.default)(color[colorVariant], opacity); } return color[colorVariant]; } if (color.darkText.indexOf(colorVariant) >= 0) { if (opacity) { return (0, _rgba2.default)('#000', opacity); } return 'rgba(0, 0, 0, .87)'; } if (opacity) { return (0, _rgba2.default)('#fff', opacity); } return 'rgba(255, 255, 255, .87)'; }); }); return style; }; var registerTheme = function registerTheme(theme, name, themeStyles) { var parsedStyle = []; themeStyles.forEach(function (style) { parsedStyle.push(parseStyle(style, theme)); }); createNewStyleElement(parsedStyle.join('\n'), name); }; var registerAllThemes = function registerAllThemes(themes, themeStyles) { var themeNames = themes ? Object.keys(themes) : []; themeNames.forEach(function (name) { registerTheme(themes[name], name, themeStyles); registeredThemes.push(name); }); }; function install(Vue) { Vue.material = new Vue({ data: function data() { return { styles: [], currentTheme: null }; }, methods: { registerTheme: function registerTheme(name, spec) { var theme = {}; if (typeof name === 'string') { theme[name] = spec; } else { theme = name; } registerAllThemes(theme, this.styles); }, applyCurrentTheme: function applyCurrentTheme(themeName) { document.body.classList.remove('md-theme-' + this.currentTheme); document.body.classList.add('md-theme-' + themeName); this.currentTheme = themeName; }, setCurrentTheme: function setCurrentTheme(themeName) { if (registeredThemes.indexOf(themeName) >= 0) { this.applyCurrentTheme(themeName); } else { if (registeredThemes.indexOf('default') === -1) { this.registerTheme('default', DEFAULT_THEME_COLORS); } else { console.warn('The theme \'' + themeName + '\' doesn\'t exists. You need to register it first in order to use.'); } this.applyCurrentTheme('default'); } } } }); Vue.component('md-theme', _MdTheme2.default); } module.exports = exports['default']; /***/ }, /* 74 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { red: { 50: '#ffebee', 100: '#ffcdd2', 200: '#ef9a9a', 300: '#e57373', 400: '#ef5350', 500: '#f44336', 600: '#e53935', 700: '#d32f2f', 800: '#c62828', 900: '#b71c1c', A100: '#ff8a80', A200: '#ff5252', A400: '#ff1744', A700: '#d50000', darkText: [50, 100, 200, 300, 'A100'] }, pink: { 50: '#fce4ec', 100: '#f8bbd0', 200: '#f48fb1', 300: '#f06292', 400: '#ec407a', 500: '#e91e63', 600: '#d81b60', 700: '#c2185b', 800: '#ad1457', 900: '#880e4f', A100: '#ff80ab', A200: '#ff4081', A400: '#f50057', A700: '#c51162', darkText: [50, 100, 200, 'A100'] }, purple: { 50: '#f3e5f5', 100: '#e1bee7', 200: '#ce93d8', 300: '#ba68c8', 400: '#ab47bc', 500: '#9c27b0', 600: '#8e24aa', 700: '#7b1fa2', 800: '#6a1b9a', 900: '#4a148c', A100: '#ea80fc', A200: '#e040fb', A400: '#d500f9', A700: '#aa00ff', darkText: [50, 100, 200, 'A100'] }, 'deep-purple': { 50: '#ede7f6', 100: '#d1c4e9', 200: '#b39ddb', 300: '#9575cd', 400: '#7e57c2', 500: '#673ab7', 600: '#5e35b1', 700: '#512da8', 800: '#4527a0', 900: '#311b92', A100: '#b388ff', A200: '#7c4dff', A400: '#651fff', A700: '#6200ea', darkText: [50, 100, 200, 'A100'] }, indigo: { 50: '#e8eaf6', 100: '#c5cae9', 200: '#9fa8da', 300: '#7986cb', 400: '#5c6bc0', 500: '#3f51b5', 600: '#3949ab', 700: '#303f9f', 800: '#283593', 900: '#1a237e', A100: '#8c9eff', A200: '#536dfe', A400: '#3d5afe', A700: '#304ffe', darkText: [50, 100, 200, 'A100'] }, blue: { 50: '#e3f2fd', 100: '#bbdefb', 200: '#90caf9', 300: '#64b5f6', 400: '#42a5f5', 500: '#2196f3', 600: '#1e88e5', 700: '#1976d2', 800: '#1565c0', 900: '#0d47a1', A100: '#82b1ff', A200: '#448aff', A400: '#2979ff', A700: '#2962ff', darkText: [50, 100, 200, 300, 400, 'A100'] }, 'light-blue': { 50: '#e1f5fe', 100: '#b3e5fc', 200: '#81d4fa', 300: '#4fc3f7', 400: '#29b6f6', 500: '#03a9f4', 600: '#039be5', 700: '#0288d1', 800: '#0277bd', 900: '#01579b', A100: '#80d8ff', A200: '#40c4ff', A400: '#00b0ff', A700: '#0091ea', darkText: [50, 100, 200, 300, 400, 500, 'A100', 'A200', 'A300'] }, cyan: { 50: '#e0f7fa', 100: '#b2ebf2', 200: '#80deea', 300: '#4dd0e1', 400: '#26c6da', 500: '#00bcd4', 600: '#00acc1', 700: '#0097a7', 800: '#00838f', 900: '#006064', A100: '#84ffff', A200: '#18ffff', A400: '#00e5ff', A700: '#00b8d4', darkText: [50, 100, 200, 300, 400, 500, 600, 'A100', 'A200', 'A300', 'A400'] }, teal: { 50: '#e0f2f1', 100: '#b2dfdb', 200: '#80cbc4', 300: '#4db6ac', 400: '#26a69a', 500: '#009688', 600: '#00897b', 700: '#00796b', 800: '#00695c', 900: '#004d40', A100: '#a7ffeb', A200: '#64ffda', A400: '#1de9b6', A700: '#00bfa5', darkText: [50, 100, 200, 300, 400, 'A100', 'A200', 'A300', 'A400'] }, green: { 50: '#e8f5e9', 100: '#c8e6c9', 200: '#a5d6a7', 300: '#81c784', 400: '#66bb6a', 500: '#4caf50', 600: '#43a047', 700: '#388e3c', 800: '#2e7d32', 900: '#1b5e20', A100: '#b9f6ca', A200: '#69f0ae', A400: '#00e676', A700: '#00c853', darkText: [50, 100, 200, 300, 400, 500, 'A100', 'A200', 'A300', 'A400'] }, 'light-green': { 50: '#f1f8e9', 100: '#dcedc8', 200: '#c5e1a5', 300: '#aed581', 400: '#9ccc65', 500: '#8bc34a', 600: '#7cb342', 700: '#689f38', 800: '#558b2f', 900: '#33691e', A100: '#ccff90', A200: '#b2ff59', A400: '#76ff03', A700: '#64dd17', darkText: [50, 100, 200, 300, 400, 500, 600, 'A100', 'A200', 'A300', 'A400'] }, lime: { 50: '#f9fbe7', 100: '#f0f4c3', 200: '#e6ee9c', 300: '#dce775', 400: '#d4e157', 500: '#cddc39', 600: '#c0ca33', 700: '#afb42b', 800: '#9e9d24', 900: '#827717', A100: '#f4ff81', A200: '#eeff41', A400: '#c6ff00', A700: '#aeea00', darkText: [50, 100, 200, 300, 400, 500, 600, 700, 800, 'A100', 'A200', 'A300', 'A400'] }, yellow: { 50: '#fffde7', 100: '#fff9c4', 200: '#fff59d', 300: '#fff176', 400: '#ffee58', 500: '#ffeb3b', 600: '#fdd835', 700: '#fbc02d', 800: '#f9a825', 900: '#f57f17', A100: '#ffff8d', A200: '#ffff00', A400: '#ffea00', A700: '#ffd600', darkText: [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 'A100', 'A200', 'A300', 'A400'] }, amber: { 50: '#fff8e1', 100: '#ffecb3', 200: '#ffe082', 300: '#ffd54f', 400: '#ffca28', 500: '#ffc107', 600: '#ffb300', 700: '#ffa000', 800: '#ff8f00', 900: '#ff6f00', A100: '#ffe57f', A200: '#ffd740', A400: '#ffc400', A700: '#ffab00', darkText: [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 'A100', 'A200', 'A300', 'A400'] }, orange: { 50: '#fff3e0', 100: '#ffe0b2', 200: '#ffcc80', 300: '#ffb74d', 400: '#ffa726', 500: '#ff9800', 600: '#fb8c00', 700: '#f57c00', 800: '#ef6c00', 900: '#e65100', A100: '#ffd180', A200: '#ffab40', A400: '#ff9100', A700: '#ff6d00', darkText: [50, 100, 200, 300, 400, 500, 600, 700, 'A100', 'A200', 'A300', 'A400'] }, 'deep-orange': { 50: '#fbe9e7', 100: '#ffccbc', 200: '#ffab91', 300: '#ff8a65', 400: '#ff7043', 500: '#ff5722', 600: '#f4511e', 700: '#e64a19', 800: '#d84315', 900: '#bf360c', A100: '#ff9e80', A200: '#ff6e40', A400: '#ff3d00', A700: '#dd2c00', darkText: [50, 100, 200, 300, 400, 'A100', 'A200'] }, brown: { 50: '#efebe9', 100: '#d7ccc8', 200: '#bcaaa4', 300: '#a1887f', 400: '#8d6e63', 500: '#795548', 600: '#6d4c41', 700: '#5d4037', 800: '#4e342e', 900: '#3e2723', A100: '#d7ccc8', A200: '#bcaaa4', A400: '#8d6e63', A700: '#5d4037', darkText: [50, 100, 200, 'A100', 'A200', 'A300', 'A400'] }, grey: { 50: '#fafafa', 100: '#f5f5f5', 200: '#eeeeee', 300: '#e0e0e0', 400: '#bdbdbd', 500: '#9e9e9e', 600: '#757575', 700: '#616161', 800: '#424242', 900: '#212121', A100: '#fff', A200: '#000000', A400: '#303030', A700: '#616161', darkText: [50, 100, 200, 300, 400, 500, 'A100'] }, 'blue-grey': { 50: '#eceff1', 100: '#cfd8dc', 200: '#b0bec5', 300: '#90a4ae', 400: '#78909c', 500: '#607d8b', 600: '#546e7a', 700: '#455a64', 800: '#37474f', 900: '#263238', A100: '#cfd8dc', A200: '#b0bec5', A400: '#78909c', A700: '#455a64', darkText: [50, 100, 200, 300, 'A100', 'A200', 'A300', 'A400'] }, white: { 50: '#fff', 100: '#fff', 200: '#fff', 300: '#fff', 400: '#fff', 500: '#fff', 600: '#fff', 700: '#fff', 800: '#fff', 900: '#fff', A100: '#fff', A200: '#fff', A400: '#fff', A700: '#fff', darkText: [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 'A100', 'A200', 'A300', 'A400'] }, black: { 50: '#000', 100: '#000', 200: '#000', 300: '#000', 400: '#000', 500: '#000', 600: '#000', 700: '#000', 800: '#000', 900: '#000', A100: '#000', A200: '#000', A400: '#000', A700: '#000', darkText: [] } }; module.exports = exports['default']; /***/ }, /* 75 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (hex, opacity) { var r = ''; var g = ''; var b = ''; var match = hex.toString().match(/^#?(([0-9a-zA-Z]{3}){1,3})$/); if (!match) { throw new Error('Invalid color' + hex); } hex = match[1]; if (hex.length === 6) { r = parseInt(hex.substring(0, 2), 16); g = parseInt(hex.substring(2, 4), 16); b = parseInt(hex.substring(4, 6), 16); } else if (hex.length === 3) { var rSubstring = hex.substring(0, 1); var gSubstring = hex.substring(1, 2); var bSubstring = hex.substring(2, 3); r = parseInt(rSubstring + rSubstring, 16); g = parseInt(gSubstring + gSubstring, 16); b = parseInt(bSubstring + bSubstring, 16); } if (opacity) { if (opacity > 1) { opacity = opacity / 100; } return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + opacity + ')'; } return 'rgb(' + r + ', ' + g + ', ' + b + ')'; }; module.exports = exports['default']; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(77) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/core/components/mdTheme/MdTheme.vue" /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-7108c965", __vue_options__) } else { hotAPI.reload("data-v-7108c965", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] MdTheme.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 77 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { props: { mdTag: String, mdName: { type: String, default: 'default' } }, data: function data() { return { name: 'md-theme' }; }, render: function render(_render) { if (this.mdTag || this.$slots.default.length > 1) { return _render(this.mdTag || 'div', { staticClass: 'md-theme' }, this.$slots.default); } return this.$slots.default[0]; } }; module.exports = exports['default']; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; __webpack_require__(79); __webpack_require__(80); function install(Vue) { var rippleParentClass = 'md-ink-ripple'; var rippleClass = 'md-ripple'; var rippleActiveClass = 'md-active'; var registeredMouseFunction = void 0; var referenceElement = void 0; var unregisterMouseEvent = function unregisterMouseEvent() { var el = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : referenceElement; el.removeEventListener('mousedown', registeredMouseFunction); }; var registerMouseEvent = function registerMouseEvent(element, holder) { if (holder) { (function () { var ripple = holder.querySelector(':scope > .' + rippleParentClass + '> .' + rippleClass); if (ripple) { registeredMouseFunction = function registeredMouseFunction(event) { var rect = holder.getBoundingClientRect(); event.stopPropagation(); ripple.classList.remove(rippleActiveClass); var top = event.pageY - rect.top - ripple.offsetHeight / 2 - document.body.scrollTop; var left = event.pageX - rect.left - ripple.offsetWidth / 2 - document.body.scrollLeft; ripple.style.top = top + 'px'; ripple.style.left = left + 'px'; ripple.classList.add(rippleActiveClass); }; element.removeEventListener('mousedown', registeredMouseFunction); element.addEventListener('mousedown', registeredMouseFunction); } })(); } }; var createElement = function createElement(ripple, className, size) { ripple = document.createElement('div'); ripple.className = className; if (size) { ripple.style.width = size; ripple.style.height = size; } return ripple; }; var checkAvailablePositions = function checkAvailablePositions(element) { var availablePositions = ['relative', 'absolute', 'fixed']; return availablePositions.indexOf(getComputedStyle(element).position) > -1; }; var getClosestParent = function getClosestParent(element) { var found = false; var parent = element; if (!element) { return false; } if (checkAvailablePositions(element)) { return element; } while (!found) { parent = parent.parentNode; if (!parent || parent.tagName.toLowerCase() === 'body') { break; } if (parent && checkAvailablePositions(parent)) { found = parent; } } return found; }; var createRipple = function createRipple(element, currentRipple) { var holder = getClosestParent(element); if (holder) { var ripple = holder.querySelector(':scope > .' + rippleParentClass + '> .' + rippleClass); if (!ripple) { var elementSize = Math.round(Math.max(holder.offsetWidth, holder.offsetHeight)) + 'px'; var rippleParent = currentRipple || createElement(ripple, rippleParentClass); var rippleElement = createElement(ripple, rippleClass, elementSize); rippleParent.appendChild(rippleElement); holder.appendChild(rippleParent); } if (holder !== element || !ripple) { referenceElement = element; registerMouseEvent(element, holder); } } }; Vue.directive('mdInkRipple', function (el, bindings) { Vue.nextTick(function () { if (!bindings.value) { createRipple(el); } else { unregisterMouseEvent(el); } }); }); Vue.component('md-ink-ripple', { props: { mdDisabled: Boolean }, render: function render(createElement) { return createElement('div', { staticClass: 'md-ink-ripple' }); }, watch: { mdDisabled: function mdDisabled() { if (this.mdDisabled) { unregisterMouseEvent(this.$el.parentNode); } else { createRipple(this.$el.parentNode, this.$el); } } }, mounted: function mounted() { if (!this.mdDisabled) { createRipple(this.$el.parentNode, this.$el); } }, destroyed: function destroyed() { unregisterMouseEvent(this.$el.parentNode); } }); } module.exports = exports['default']; /***/ }, /* 79 */ /***/ function(module, exports) { /* scopeQuerySelectorShim.js * * Copyright (C) 2015 Larry Davis * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ (function() { if (!HTMLElement.prototype.querySelectorAll) { throw new Error("rootedQuerySelectorAll: This polyfill can only be used with browsers that support querySelectorAll"); } // A temporary element to query against for elements not currently in the DOM // We'll also use this element to test for :scope support var container = document.createElement("div"); // Check if the browser supports :scope try { // Browser supports :scope, do nothing container.querySelectorAll(":scope *"); } catch (e) { // Match usage of scope var scopeRE = /^\s*:scope/gi; // Overrides function overrideNodeMethod(prototype, methodName) { // Store the old method for use later var oldMethod = prototype[methodName]; // Override the method prototype[methodName] = function(query) { var nodeList, gaveId = false, gaveContainer = false; if (query.match(scopeRE)) { // Remove :scope query = query.replace(scopeRE, ""); if (!this.parentNode) { // Add to temporary container container.appendChild(this); gaveContainer = true; } parentNode = this.parentNode; if (!this.id) { // Give temporary ID this.id = "rootedQuerySelector_id_" + new Date().getTime(); gaveId = true; } // Find elements against parent node nodeList = oldMethod.call(parentNode, "#" + this.id + " " + query); // Reset the ID if (gaveId) { this.id = ""; } // Remove from temporary container if (gaveContainer) { container.removeChild(this); } return nodeList; } else { // No immediate child selector used return oldMethod.call(this, query); } }; } // Browser doesn't support :scope, add polyfill overrideNodeMethod(HTMLElement.prototype, "querySelector"); overrideNodeMethod(HTMLElement.prototype, "querySelectorAll"); } })(); /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(81) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/core/components/mdInkRipple/mdInkRipple.vue" if (__vue_options__.functional) {console.error("[vue-loader] mdInkRipple.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 81 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 82 */ /***/ function(module, exports) { module.exports = ".THEME_NAME :not(input):not(textarea)::selection {\n background: ACCENT-COLOR;\n color: ACCENT-CONTRAST; }\n\n.THEME_NAME a:not(.md-button) {\n color: ACCENT-COLOR; }\n .THEME_NAME a:not(.md-button):hover {\n color: ACCENT-COLOR-800; }\n\nbody.THEME_NAME {\n background-color: BACKGROUND-COLOR-A100;\n color: BACKGROUND-CONTRAST-0.87; }\n\n/* Typography */\n.THEME_NAME .md-caption,\n.THEME_NAME .md-display-1,\n.THEME_NAME .md-display-2,\n.THEME_NAME .md-display-3,\n.THEME_NAME .md-display-4 {\n color: BACKGROUND-CONTRAST-0.57; }\n\n.THEME_NAME code:not(.hljs) {\n background-color: ACCENT-COLOR-A100-0.2;\n color: ACCENT-COLOR-800; }\n" /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(84); if(typeof content === 'string') content = [[module.id, content, '']]; // add the styles to the DOM var update = __webpack_require__(85)(content, {}); if(content.locals) module.exports = content.locals; // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!./../../../node_modules/css-loader/index.js!./../../../node_modules/sass-loader/index.js!./core.scss", function() { var newContent = require("!!./../../../node_modules/css-loader/index.js!./../../../node_modules/sass-loader/index.js!./core.scss"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(4)(); // imports // module exports.push([module.id, "/* Common */\n/* Responsive Breakpoints */\n/* Transitions - Based on Angular Material */\n/* Elevation - Based on Angular Material */\n/* Structure\n ========================================================================== */\nhtml {\n height: 100%;\n box-sizing: border-box; }\n html *,\n html *:before,\n html *:after {\n box-sizing: inherit; }\n\nbody {\n min-height: 100%;\n margin: 0;\n position: relative;\n -webkit-tap-highlight-color: transparent;\n -webkit-touch-callout: none;\n -webkit-text-size-adjust: 100%;\n -ms-text-size-adjust: 100%;\n -moz-osx-font-smoothing: grayscale;\n -webkit-font-smoothing: antialiased;\n color: rgba(0, 0, 0, 0.87);\n font-family: Roboto, \"Noto Sans\", Noto, sans-serif; }\n\n[tabindex='-1']:focus {\n outline: none; }\n\n/* Fluid Media\n ========================================================================== */\naudio,\nimg,\nsvg,\nobject,\nembed,\ncanvas,\nvideo,\niframe {\n max-width: 100%;\n height: auto;\n font-style: italic;\n vertical-align: middle; }\n\n/* Suppress the focus outline on links that cannot be accessed via keyboard.\n This prevents an unwanted focus outline from appearing around elements\n that might still respond to pointer events.\n ========================================================================== */\n[tabindex=\"-1\"]:focus {\n outline: none !important; }\n\n.md-scrollbar::-webkit-scrollbar,\n.md-scrollbar ::-webkit-scrollbar {\n width: 10px;\n height: 10px;\n box-shadow: inset 1px 1px 0 rgba(0, 0, 0, 0.12);\n transition: all 0.5s cubic-bezier(0.35, 0, 0.25, 1);\n background-color: rgba(0, 0, 0, 0.05); }\n .md-scrollbar::-webkit-scrollbar:hover,\n .md-scrollbar ::-webkit-scrollbar:hover {\n box-shadow: inset 1px 1px 0 rgba(0, 0, 0, 0.054), inset 0 -1px 0 rgba(0, 0, 0, 0.038);\n background-color: rgba(0, 0, 0, 0.087); }\n\n.md-scrollbar::-webkit-scrollbar-button,\n.md-scrollbar ::-webkit-scrollbar-button {\n display: none; }\n\n.md-scrollbar::-webkit-scrollbar-corner,\n.md-scrollbar ::-webkit-scrollbar-corner {\n background-color: transparent; }\n\n.md-scrollbar::-webkit-scrollbar-thumb,\n.md-scrollbar ::-webkit-scrollbar-thumb {\n background-color: rgba(0, 0, 0, 0.26);\n box-shadow: inset 1px 1px 0 rgba(0, 0, 0, 0.054), inset 0 -1px 0 rgba(0, 0, 0, 0.087);\n transition: all 0.5s cubic-bezier(0.35, 0, 0.25, 1); }\n\n/* Text and Titles\n ========================================================================== */\n.md-caption {\n font-size: 12px;\n font-weight: 400;\n letter-spacing: .02em;\n line-height: 17px; }\n\n.md-body-1, body {\n font-size: 14px;\n font-weight: 400;\n letter-spacing: .01em;\n line-height: 20px; }\n\n.md-body-2 {\n font-size: 14px;\n font-weight: 500;\n letter-spacing: .01em;\n line-height: 24px; }\n\n.md-subheading {\n font-size: 16px;\n font-weight: 400;\n letter-spacing: .01em;\n line-height: 24px; }\n\n.md-title {\n font-size: 20px;\n font-weight: 500;\n letter-spacing: .005em;\n line-height: 26px; }\n\n.md-headline {\n font-size: 24px;\n font-weight: 400;\n letter-spacing: 0;\n line-height: 32px; }\n\n.md-display-1 {\n font-size: 34px;\n font-weight: 400;\n letter-spacing: 0;\n line-height: 40px; }\n\n.md-display-2 {\n font-size: 45px;\n font-weight: 400;\n letter-spacing: 0;\n line-height: 48px; }\n\n.md-display-3 {\n font-size: 56px;\n font-weight: 400;\n letter-spacing: -.005em;\n line-height: 58px; }\n\n.md-display-4 {\n font-size: 112px;\n font-weight: 300;\n letter-spacing: -.01em;\n line-height: 112px; }\n\n/* Links & Buttons\n ========================================================================== */\na:not(.md-button):not(.md-bottom-bar-item) {\n text-decoration: none; }\n a:not(.md-button):not(.md-bottom-bar-item):hover {\n text-decoration: underline; }\n\nbutton:focus {\n outline: none; }\n", ""]); // exports /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var stylesInDom = {}, memoize = function(fn) { var memo; return function () { if (typeof memo === "undefined") memo = fn.apply(this, arguments); return memo; }; }, isOldIE = memoize(function() { return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase()); }), getHeadElement = memoize(function () { return document.head || document.getElementsByTagName("head")[0]; }), singletonElement = null, singletonCounter = 0, styleElementsInsertedAtTop = []; module.exports = function(list, options) { if(false) { if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment"); } options = options || {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style> // tags it will allow on a page if (typeof options.singleton === "undefined") options.singleton = isOldIE(); // By default, add <style> tags to the bottom of <head>. if (typeof options.insertAt === "undefined") options.insertAt = "bottom"; var styles = listToStyles(list); addStylesToDom(styles, options); return function update(newList) { var mayRemove = []; for(var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; domStyle.refs--; mayRemove.push(domStyle); } if(newList) { var newStyles = listToStyles(newList); addStylesToDom(newStyles, options); } for(var i = 0; i < mayRemove.length; i++) { var domStyle = mayRemove[i]; if(domStyle.refs === 0) { for(var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j](); delete stylesInDom[domStyle.id]; } } }; } function addStylesToDom(styles, options) { for(var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; if(domStyle) { domStyle.refs++; for(var j = 0; j < domStyle.parts.length; j++) { domStyle.parts[j](item.parts[j]); } for(; j < item.parts.length; j++) { domStyle.parts.push(addStyle(item.parts[j], options)); } } else { var parts = []; for(var j = 0; j < item.parts.length; j++) { parts.push(addStyle(item.parts[j], options)); } stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts}; } } } function listToStyles(list) { var styles = []; var newStyles = {}; for(var i = 0; i < list.length; i++) { var item = list[i]; var id = item[0]; var css = item[1]; var media = item[2]; var sourceMap = item[3]; var part = {css: css, media: media, sourceMap: sourceMap}; if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]}); else newStyles[id].parts.push(part); } return styles; } function insertStyleElement(options, styleElement) { var head = getHeadElement(); var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1]; if (options.insertAt === "top") { if(!lastStyleElementInsertedAtTop) { head.insertBefore(styleElement, head.firstChild); } else if(lastStyleElementInsertedAtTop.nextSibling) { head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling); } else { head.appendChild(styleElement); } styleElementsInsertedAtTop.push(styleElement); } else if (options.insertAt === "bottom") { head.appendChild(styleElement); } else { throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'."); } } function removeStyleElement(styleElement) { styleElement.parentNode.removeChild(styleElement); var idx = styleElementsInsertedAtTop.indexOf(styleElement); if(idx >= 0) { styleElementsInsertedAtTop.splice(idx, 1); } } function createStyleElement(options) { var styleElement = document.createElement("style"); styleElement.type = "text/css"; insertStyleElement(options, styleElement); return styleElement; } function addStyle(obj, options) { var styleElement, update, remove; if (options.singleton) { var styleIndex = singletonCounter++; styleElement = singletonElement || (singletonElement = createStyleElement(options)); update = applyToSingletonTag.bind(null, styleElement, styleIndex, false); remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true); } else { styleElement = createStyleElement(options); update = applyToTag.bind(null, styleElement); remove = function() { removeStyleElement(styleElement); }; } update(obj); return function updateStyle(newObj) { if(newObj) { if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) return; update(obj = newObj); } else { remove(); } }; } var replaceText = (function () { var textStore = []; return function (index, replacement) { textStore[index] = replacement; return textStore.filter(Boolean).join('\n'); }; })(); function applyToSingletonTag(styleElement, index, remove, obj) { var css = remove ? "" : obj.css; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = replaceText(index, css); } else { var cssNode = document.createTextNode(css); var childNodes = styleElement.childNodes; if (childNodes[index]) styleElement.removeChild(childNodes[index]); if (childNodes.length) { styleElement.insertBefore(cssNode, childNodes[index]); } else { styleElement.appendChild(cssNode); } } } function applyToTag(styleElement, obj) { var css = obj.css; var media = obj.media; var sourceMap = obj.sourceMap; if (media) { styleElement.setAttribute("media", media); } if (sourceMap) { // https://developer.chrome.com/devtools/docs/javascript-debugging // this makes source maps inside style tags work properly in Chrome css += '\n/*# sourceURL=' + sourceMap.sources[0] + ' */'; // http://stackoverflow.com/a/26603875 css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */"; } if (styleElement.styleSheet) { styleElement.styleSheet.cssText = css; } else { while(styleElement.firstChild) { styleElement.removeChild(styleElement.firstChild); } styleElement.appendChild(document.createTextNode(css)); } } /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdDialog = __webpack_require__(87); var _mdDialog2 = _interopRequireDefault(_mdDialog); var _mdDialogTitle = __webpack_require__(92); var _mdDialogTitle2 = _interopRequireDefault(_mdDialogTitle); var _mdDialogContent = __webpack_require__(94); var _mdDialogContent2 = _interopRequireDefault(_mdDialogContent); var _mdDialogActions = __webpack_require__(96); var _mdDialogActions2 = _interopRequireDefault(_mdDialogActions); var _mdDialogAlert = __webpack_require__(98); var _mdDialogAlert2 = _interopRequireDefault(_mdDialogAlert); var _mdDialogConfirm = __webpack_require__(101); var _mdDialogConfirm2 = _interopRequireDefault(_mdDialogConfirm); var _mdDialogPrompt = __webpack_require__(104); var _mdDialogPrompt2 = _interopRequireDefault(_mdDialogPrompt); var _mdDialog3 = __webpack_require__(107); var _mdDialog4 = _interopRequireDefault(_mdDialog3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-dialog', Vue.extend(_mdDialog2.default)); Vue.component('md-dialog-title', Vue.extend(_mdDialogTitle2.default)); Vue.component('md-dialog-content', Vue.extend(_mdDialogContent2.default)); Vue.component('md-dialog-actions', Vue.extend(_mdDialogActions2.default)); /* Presets */ Vue.component('md-dialog-alert', Vue.extend(_mdDialogAlert2.default)); Vue.component('md-dialog-confirm', Vue.extend(_mdDialogConfirm2.default)); Vue.component('md-dialog-prompt', Vue.extend(_mdDialogPrompt2.default)); Vue.material.styles.push(_mdDialog4.default); } module.exports = exports['default']; /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(88) /* script */ __vue_exports__ = __webpack_require__(89) /* template */ var __vue_template__ = __webpack_require__(91) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdDialog/mdDialog.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-78b956ed", __vue_options__) } else { hotAPI.reload("data-v-78b956ed", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdDialog.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 88 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); var _transitionEndEventName = __webpack_require__(90); var _transitionEndEventName2 = _interopRequireDefault(_transitionEndEventName); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // // // // // // // // // // // // exports.default = { props: { mdClickOutsideToClose: { type: Boolean, default: true }, mdEscToClose: { type: Boolean, default: true }, mdBackdrop: { type: Boolean, default: true }, mdOpenFrom: String, mdCloseTo: String, mdFullscreen: { type: Boolean, default: false } }, mixins: [_mixin2.default], data: function data() { return { active: false, transitionOff: false, dialogTransform: '' }; }, computed: { classes: function classes() { return { 'md-active': this.active }; }, dialogClasses: function dialogClasses() { return { 'md-fullscreen': this.mdFullscreen, 'md-transition-off': this.transitionOff, 'md-reference': this.mdOpenFrom || this.mdCloseTo }; }, styles: function styles() { return { transform: this.dialogTransform }; } }, methods: { removeDialog: function removeDialog() { if (this.rootElement.contains(this.dialogElement)) { this.$el.parentNode.removeChild(this.$el); } }, calculateDialogPos: function calculateDialogPos(ref) { var reference = document.querySelector(ref); if (reference) { var openFromRect = reference.getBoundingClientRect(); var dialogRect = this.dialogInnerElement.getBoundingClientRect(); var widthInScale = openFromRect.width / dialogRect.width; var heightInScale = openFromRect.height / dialogRect.height; var distance = { top: -(dialogRect.top - openFromRect.top), left: -(dialogRect.left - openFromRect.left + openFromRect.width) }; if (openFromRect.top > dialogRect.top + dialogRect.height) { distance.top = openFromRect.top - dialogRect.top; } if (openFromRect.left > dialogRect.left + dialogRect.width) { distance.left = openFromRect.left - dialogRect.left - openFromRect.width; } this.dialogTransform = 'translate3D(' + distance.left + 'px, ' + distance.top + 'px, 0) scale(' + widthInScale + ', ' + heightInScale + ')'; } }, open: function open() { var _this = this; this.rootElement.appendChild(this.dialogElement); this.transitionOff = true; this.calculateDialogPos(this.mdOpenFrom); window.setTimeout(function () { _this.dialogElement.focus(); _this.transitionOff = false; _this.active = true; }); this.$emit('open'); }, closeOnEsc: function closeOnEsc() { if (this.mdEscToClose) { this.close(); } }, close: function close() { var _this2 = this; if (this.rootElement.contains(this.dialogElement)) { this.$nextTick(function () { var cleanElement = function cleanElement() { var activeRipple = _this2.dialogElement.querySelector('.md-ripple.md-active'); if (activeRipple) { activeRipple.classList.remove('md-active'); } _this2.dialogInnerElement.removeEventListener(_transitionEndEventName2.default, cleanElement); _this2.rootElement.removeChild(_this2.dialogElement); _this2.dialogTransform = ''; }; _this2.transitionOff = true; _this2.dialogTransform = ''; _this2.calculateDialogPos(_this2.mdCloseTo); window.setTimeout(function () { _this2.transitionOff = false; _this2.active = false; _this2.dialogInnerElement.addEventListener(_transitionEndEventName2.default, cleanElement); }); _this2.$emit('close'); }); } } }, mounted: function mounted() { var _this3 = this; this.$nextTick(function () { _this3.rootElement = _this3.$root.$el; _this3.dialogElement = _this3.$el; _this3.dialogInnerElement = _this3.$refs.dialog; _this3.removeDialog(); }); }, beforeDestroy: function beforeDestroy() { this.removeDialog(); } }; module.exports = exports['default']; /***/ }, /* 90 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function transitionEndEventName() { var el = document.createElement('span'); var transitions = { transition: 'transitionend', OTransition: 'oTransitionEnd', MozTransition: 'transitionend', WebkitTransition: 'webkitTransitionEnd' }; for (var transition in transitions) { if (el.style[transition] !== undefined) { return transitions[transition]; } } } exports.default = transitionEndEventName(); module.exports = exports['default']; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-dialog-container", class: [_vm.themeClass, _vm.classes], attrs: { "tabindex": "0" }, on: { "keyup": function($event) { if (_vm._k($event.keyCode, "esc", 27)) { return; } $event.stopPropagation(); _vm.closeOnEsc($event) } } }, [_c('div', { ref: "dialog", staticClass: "md-dialog", class: _vm.dialogClasses, style: (_vm.styles) }, [_vm._t("default")], true), _vm._v(" "), (_vm.mdBackdrop) ? _c('md-backdrop', { ref: "backdrop", staticClass: "md-dialog-backdrop", class: _vm.classes, on: { "close": function($event) { _vm.mdClickOutsideToClose && _vm.close() } } }) : _vm._e()]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-78b956ed", module.exports) } } /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* template */ var __vue_template__ = __webpack_require__(93) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdDialog/mdDialogTitle.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-0083d19b", __vue_options__) } else { hotAPI.reload("data-v-0083d19b", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdDialogTitle.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-dialog-title md-title" }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-0083d19b", module.exports) } } /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* template */ var __vue_template__ = __webpack_require__(95) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdDialog/mdDialogContent.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-10712708", __vue_options__) } else { hotAPI.reload("data-v-10712708", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdDialogContent.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-dialog-content" }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-10712708", module.exports) } } /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* template */ var __vue_template__ = __webpack_require__(97) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdDialog/mdDialogActions.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-6e6a9f00", __vue_options__) } else { hotAPI.reload("data-v-6e6a9f00", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdDialogActions.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-dialog-actions" }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-6e6a9f00", module.exports) } } /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(99) /* template */ var __vue_template__ = __webpack_require__(100) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdDialog/presets/mdDialogAlert.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-e4165678", __vue_options__) } else { hotAPI.reload("data-v-e4165678", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdDialogAlert.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 99 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // // // // // // // // exports.default = { props: { mdTitle: String, mdContent: String, mdContentHtml: String, mdOkText: { type: String, default: 'Ok' } }, data: function data() { return { debounce: false }; }, methods: { fireCloseEvent: function fireCloseEvent() { if (!this.debounce) { this.$emit('close'); } }, open: function open() { this.$emit('open'); this.debounce = false; this.$refs.dialog.open(); }, close: function close() { this.fireCloseEvent(); this.debounce = true; this.$refs.dialog.close(); } }, mounted: function mounted() { if (!this.mdContent && !this.mdContentHtml) { throw new Error('Missing md-content or md-content-html attributes'); } } }; module.exports = exports['default']; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('md-dialog', { ref: "dialog", staticClass: "md-dialog-alert", on: { "close": function($event) { _vm.fireCloseEvent() } } }, [(_vm.mdTitle) ? _c('md-dialog-title', [_vm._v(_vm._s(_vm.mdTitle))]) : _vm._e(), _vm._v(" "), (_vm.mdContentHtml) ? _c('md-dialog-content', { domProps: { "innerHTML": _vm._s(_vm.mdContentHtml) } }) : _c('md-dialog-content', [_vm._v(_vm._s(_vm.mdContent))]), _vm._v(" "), _vm._v(" "), _c('md-dialog-actions', [_c('md-button', { staticClass: "md-primary", on: { "click": function($event) { _vm.close() } } }, [_vm._v(_vm._s(_vm.mdOkText))])])]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-e4165678", module.exports) } } /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(102) /* template */ var __vue_template__ = __webpack_require__(103) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdDialog/presets/mdDialogConfirm.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-70186c28", __vue_options__) } else { hotAPI.reload("data-v-70186c28", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdDialogConfirm.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 102 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // // // // // // // // // exports.default = { props: { mdTitle: String, mdContent: String, mdContentHtml: String, mdOkText: { type: String, default: 'Ok' }, mdCancelText: { type: String, default: 'Cancel' } }, data: function data() { return { debounce: false }; }, methods: { fireCloseEvent: function fireCloseEvent(type) { if (!this.debounce) { this.$emit('close', type); } }, open: function open() { this.$emit('open'); this.debounce = false; this.$refs.dialog.open(); }, close: function close(type) { this.fireCloseEvent(type); this.debounce = true; this.$refs.dialog.close(); } }, mounted: function mounted() { if (!this.mdContent && !this.mdContentHtml) { throw new Error('Missing md-content or md-content-html attributes'); } } }; module.exports = exports['default']; /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('md-dialog', { ref: "dialog", staticClass: "md-dialog-confirm", on: { "close": function($event) { _vm.fireCloseEvent('cancel') } } }, [(_vm.mdTitle) ? _c('md-dialog-title', [_vm._v(_vm._s(_vm.mdTitle))]) : _vm._e(), _vm._v(" "), (_vm.mdContentHtml) ? _c('md-dialog-content', { domProps: { "innerHTML": _vm._s(_vm.mdContentHtml) } }) : _c('md-dialog-content', [_vm._v(_vm._s(_vm.mdContent))]), _vm._v(" "), _vm._v(" "), _c('md-dialog-actions', [_c('md-button', { staticClass: "md-primary", on: { "click": function($event) { _vm.close('cancel') } } }, [_vm._v(_vm._s(_vm.mdCancelText))]), _vm._v(" "), _c('md-button', { staticClass: "md-primary", on: { "click": function($event) { _vm.close('ok') } } }, [_vm._v(_vm._s(_vm.mdOkText))])])]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-70186c28", module.exports) } } /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(105) /* template */ var __vue_template__ = __webpack_require__(106) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdDialog/presets/mdDialogPrompt.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-047e25a8", __vue_options__) } else { hotAPI.reload("data-v-047e25a8", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdDialogPrompt.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 105 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // // // // // // // // // // // // // // // // // // // // // // exports.default = { props: { value: { type: [String, Number], required: true }, mdTitle: String, mdContent: String, mdContentHtml: String, mdOkText: { type: String, default: 'Ok' }, mdCancelText: { type: String, default: 'Cancel' }, mdInputId: String, mdInputName: String, mdInputMaxlength: [String, Number], mdInputPlaceholder: String }, data: function data() { return { debounce: false }; }, methods: { fireCloseEvent: function fireCloseEvent(type) { if (!this.debounce) { this.$emit('close', type); } }, open: function open() { var _this = this; this.$emit('open'); this.debounce = false; this.$refs.dialog.open(); window.setTimeout(function () { _this.$refs.input.$el.focus(); }); }, close: function close(type) { this.fireCloseEvent(type); this.debounce = true; this.$refs.dialog.close(); }, confirmValue: function confirmValue() { this.$emit('input', this.$refs.input.$el.value); this.close('ok'); } } }; module.exports = exports['default']; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('md-dialog', { ref: "dialog", staticClass: "md-dialog-prompt", on: { "close": function($event) { _vm.fireCloseEvent('cancel') } } }, [(_vm.mdTitle) ? _c('md-dialog-title', [_vm._v(_vm._s(_vm.mdTitle))]) : _vm._e(), _vm._v(" "), (_vm.mdContentHtml) ? _c('md-dialog-content', { domProps: { "innerHTML": _vm._s(_vm.mdContentHtml) } }) : _vm._e(), _vm._v(" "), (_vm.mdContent) ? _c('md-dialog-content', [_vm._v(_vm._s(_vm.mdContent))]) : _vm._e(), _vm._v(" "), _c('md-dialog-content', [_c('md-input-container', [_c('md-input', { ref: "input", attrs: { "id": _vm.mdInputId, "name": _vm.mdInputName, "maxlength": _vm.mdInputMaxlength, "placeholder": _vm.mdInputPlaceholder, "value": _vm.value }, nativeOn: { "keydown": function($event) { if (_vm._k($event.keyCode, "enter", 13)) { return; } _vm.confirmValue($event) } } })])]), _vm._v(" "), _c('md-dialog-actions', [_c('md-button', { staticClass: "md-primary", on: { "click": function($event) { _vm.close('cancel') } } }, [_vm._v(_vm._s(_vm.mdCancelText))]), _vm._v(" "), _c('md-button', { staticClass: "md-primary", on: { "click": _vm.confirmValue } }, [_vm._v(_vm._s(_vm.mdOkText))])])]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-047e25a8", module.exports) } } /***/ }, /* 107 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-dialog-container .md-dialog {\n background-color: BACKGROUND-COLOR-A100;\n color: BACKGROUND-CONTRAST; }\n" /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdDivider = __webpack_require__(109); var _mdDivider2 = _interopRequireDefault(_mdDivider); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-divider', Vue.extend(_mdDivider2.default)); } module.exports = exports['default']; /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(110) /* template */ var __vue_template__ = __webpack_require__(111) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdDivider/mdDivider.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-30e870da", __vue_options__) } else { hotAPI.reload("data-v-30e870da", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdDivider.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 110 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('hr', { staticClass: "md-divider" }) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-30e870da", module.exports) } } /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdIcon = __webpack_require__(113); var _mdIcon2 = _interopRequireDefault(_mdIcon); var _mdIcon3 = __webpack_require__(117); var _mdIcon4 = _interopRequireDefault(_mdIcon3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-icon', Vue.extend(_mdIcon2.default)); Vue.material.styles.push(_mdIcon4.default); } module.exports = exports['default']; /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(114) /* script */ __vue_exports__ = __webpack_require__(115) /* template */ var __vue_template__ = __webpack_require__(116) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdIcon/mdIcon.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-f5836666", __vue_options__) } else { hotAPI.reload("data-v-f5836666", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdIcon.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 114 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { mixins: [_mixin2.default] }; // // // // // // // // module.exports = exports['default']; /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('i', { staticClass: "md-icon material-icons", class: [_vm.themeClass] }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-f5836666", module.exports) } } /***/ }, /* 117 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-icon.md-primary {\n color: PRIMARY-COLOR; }\n\n.THEME_NAME.md-icon.md-accent {\n color: ACCENT-COLOR; }\n\n.THEME_NAME.md-icon.md-warn {\n color: WARN-COLOR; }\n" /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdInputContainer = __webpack_require__(119); var _mdInputContainer2 = _interopRequireDefault(_mdInputContainer); var _mdInput = __webpack_require__(124); var _mdInput2 = _interopRequireDefault(_mdInput); var _mdTextarea = __webpack_require__(129); var _mdTextarea2 = _interopRequireDefault(_mdTextarea); var _mdInputContainer3 = __webpack_require__(133); var _mdInputContainer4 = _interopRequireDefault(_mdInputContainer3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-input-container', _mdInputContainer2.default); Vue.component('md-input', _mdInput2.default); Vue.component('md-textarea', _mdTextarea2.default); Vue.material.styles.push(_mdInputContainer4.default); } module.exports = exports['default']; /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(120) /* script */ __vue_exports__ = __webpack_require__(121) /* template */ var __vue_template__ = __webpack_require__(123) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdInputContainer/mdInputContainer.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-4e747acd", __vue_options__) } else { hotAPI.reload("data-v-4e747acd", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdInputContainer.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 120 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); var _isArray = __webpack_require__(122); var _isArray2 = _interopRequireDefault(_isArray); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // // // // // // // // // // // // // // exports.default = { props: { mdInline: Boolean, mdHasPassword: Boolean }, mixins: [_mixin2.default], data: function data() { return { value: '', input: false, showPassword: false, enableCounter: false, hasSelect: false, hasPlaceholder: false, isDisabled: false, isRequired: false, isFocused: false, counterLength: 0, inputLength: 0 }; }, computed: { hasValue: function hasValue() { if ((0, _isArray2.default)(this.value)) { return this.value.length > 0; } return Boolean(this.value); }, classes: function classes() { return { 'md-input-inline': this.mdInline, 'md-has-password': this.mdHasPassword, 'md-has-select': this.hasSelect, 'md-has-value': this.hasValue, 'md-input-placeholder': this.hasPlaceholder, 'md-input-disabled': this.isDisabled, 'md-input-required': this.isRequired, 'md-input-focused': this.isFocused }; } }, methods: { isInput: function isInput() { return this.input && this.input.tagName.toLowerCase() === 'input'; }, togglePasswordType: function togglePasswordType() { if (this.isInput()) { if (this.input.type === 'password') { this.input.type = 'text'; this.showPassword = true; } else { this.input.type = 'password'; this.showPassword = false; } this.input.focus(); } }, setValue: function setValue(value) { this.value = value; } }, mounted: function mounted() { this.input = this.$el.querySelectorAll('input, textarea, select')[0]; if (!this.input) { this.$destroy(); throw new Error('Missing input/select/textarea inside md-input-container'); } } }; module.exports = exports['default']; /***/ }, /* 122 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var isArray = function isArray(value) { return value && value.constructor === Array; }; exports.default = isArray; module.exports = exports["default"]; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-input-container", class: [_vm.themeClass, _vm.classes] }, [_vm._t("default"), _vm._v(" "), (_vm.enableCounter) ? _c('span', { staticClass: "md-count" }, [_vm._v(_vm._s(_vm.inputLength) + " / " + _vm._s(_vm.counterLength))]) : _vm._e(), _vm._v(" "), (_vm.mdHasPassword) ? _c('md-button', { staticClass: "md-icon-button md-toggle-password", on: { "click": _vm.togglePasswordType } }, [_c('md-icon', [_vm._v(_vm._s(_vm.showPassword ? 'visibility_off' : 'visibility'))])]) : _vm._e()], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-4e747acd", module.exports) } } /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(125) /* template */ var __vue_template__ = __webpack_require__(128) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdInputContainer/mdInput.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-53a56078", __vue_options__) } else { hotAPI.reload("data-v-53a56078", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdInput.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _common = __webpack_require__(126); var _common2 = _interopRequireDefault(_common); var _getClosestVueParent = __webpack_require__(127); var _getClosestVueParent2 = _interopRequireDefault(_getClosestVueParent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // // // // // // // // // // // // // // // // exports.default = { mixins: [_common2.default], props: { type: { type: String, default: 'text' } }, mounted: function mounted() { this.parentContainer = (0, _getClosestVueParent2.default)(this.$parent, 'md-input-container'); if (!this.parentContainer) { this.$destroy(); throw new Error('You should wrap the md-input in a md-input-container'); } this.setParentDisabled(); this.setParentRequired(); this.setParentPlaceholder(); this.setParentValue(); this.handleMaxLength(); } }; module.exports = exports['default']; /***/ }, /* 126 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { props: { value: [String, Number], disabled: Boolean, required: Boolean, maxlength: [Number, String], placeholder: String }, watch: { value: function value(_value) { this.setParentValue(_value); }, disabled: function disabled() { this.setParentDisabled(); }, required: function required() { this.setParentRequired(); }, placeholder: function placeholder() { this.setParentPlaceholder(); }, maxlength: function maxlength() { this.handleMaxLength(); } }, methods: { handleMaxLength: function handleMaxLength() { this.parentContainer.enableCounter = this.maxlength > 0; this.parentContainer.counterLength = this.maxlength; }, setParentValue: function setParentValue(value) { this.parentContainer.setValue(value || this.$el.value); }, setParentDisabled: function setParentDisabled() { this.parentContainer.isDisabled = this.disabled; }, setParentRequired: function setParentRequired() { this.parentContainer.isRequired = this.required; }, setParentPlaceholder: function setParentPlaceholder() { this.parentContainer.hasPlaceholder = !!this.placeholder; }, onFocus: function onFocus() { this.parentContainer.isFocused = true; }, onBlur: function onBlur() { this.parentContainer.isFocused = false; this.setParentValue(); }, onInput: function onInput() { var value = this.$el.value; this.setParentValue(); this.parentContainer.inputLength = value ? value.length : 0; this.$emit('change', value); this.$emit('input', value); } } }; module.exports = exports['default']; /***/ }, /* 127 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var getClosestVueParent = function getClosestVueParent($parent, cssClass) { if (!$parent || !$parent.$el) { return false; } if ($parent._uid === 0) { return false; } if ($parent.$el.classList.contains(cssClass)) { return $parent; } return getClosestVueParent($parent.$parent, cssClass); }; exports.default = getClosestVueParent; module.exports = exports["default"]; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('input', { staticClass: "md-input", attrs: { "type": _vm.type, "disabled": _vm.disabled, "required": _vm.required, "placeholder": _vm.placeholder, "maxlength": _vm.maxlength }, domProps: { "value": _vm.value }, on: { "focus": _vm.onFocus, "blur": _vm.onBlur, "input": _vm.onInput, "keydown": [function($event) { if (_vm._k($event.keyCode, "up", 38)) { return; } _vm.onInput($event) }, function($event) { if (_vm._k($event.keyCode, "down", 40)) { return; } _vm.onInput($event) }] } }) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-53a56078", module.exports) } } /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(130) /* template */ var __vue_template__ = __webpack_require__(132) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdInputContainer/mdTextarea.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-62d24f30", __vue_options__) } else { hotAPI.reload("data-v-62d24f30", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdTextarea.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _autosize = __webpack_require__(131); var _autosize2 = _interopRequireDefault(_autosize); var _common = __webpack_require__(126); var _common2 = _interopRequireDefault(_common); var _getClosestVueParent = __webpack_require__(127); var _getClosestVueParent2 = _interopRequireDefault(_getClosestVueParent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { mixins: [_common2.default], watch: { value: function value() { var _this = this; this.$nextTick(function () { _autosize2.default.update(_this.$el); }); } }, mounted: function mounted() { this.parentContainer = (0, _getClosestVueParent2.default)(this.$parent, 'md-input-container'); if (!this.parentContainer) { this.$destroy(); throw new Error('You should wrap the md-textarea in a md-input-container'); } this.setParentDisabled(); this.setParentRequired(); this.setParentPlaceholder(); this.setParentValue(); this.handleMaxLength(); if (!this.$el.getAttribute('rows')) { this.$el.setAttribute('rows', '1'); } (0, _autosize2.default)(this.$el); }, beforeDestroy: function beforeDestroy() { _autosize2.default.destroy(this.$el); } }; // // // // // // // // // // // // // module.exports = exports['default']; /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Autosize 3.0.20 license: MIT http://www.jacklmoore.com/autosize */ (function (global, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, module], __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 !== 'undefined' && typeof module !== 'undefined') { factory(exports, module); } else { var mod = { exports: {} }; factory(mod.exports, mod); global.autosize = mod.exports; } })(this, function (exports, module) { 'use strict'; var map = typeof Map === "function" ? new Map() : (function () { var keys = []; var values = []; return { has: function has(key) { return keys.indexOf(key) > -1; }, get: function get(key) { return values[keys.indexOf(key)]; }, set: function set(key, value) { if (keys.indexOf(key) === -1) { keys.push(key); values.push(value); } }, 'delete': function _delete(key) { var index = keys.indexOf(key); if (index > -1) { keys.splice(index, 1); values.splice(index, 1); } } }; })(); var createEvent = function createEvent(name) { return new Event(name, { bubbles: true }); }; try { new Event('test'); } catch (e) { // IE does not support `new Event()` createEvent = function (name) { var evt = document.createEvent('Event'); evt.initEvent(name, true, false); return evt; }; } function assign(ta) { if (!ta || !ta.nodeName || ta.nodeName !== 'TEXTAREA' || map.has(ta)) return; var heightOffset = null; var clientWidth = ta.clientWidth; var cachedHeight = null; function init() { var style = window.getComputedStyle(ta, null); if (style.resize === 'vertical') { ta.style.resize = 'none'; } else if (style.resize === 'both') { ta.style.resize = 'horizontal'; } if (style.boxSizing === 'content-box') { heightOffset = -(parseFloat(style.paddingTop) + parseFloat(style.paddingBottom)); } else { heightOffset = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth); } // Fix when a textarea is not on document body and heightOffset is Not a Number if (isNaN(heightOffset)) { heightOffset = 0; } update(); } function changeOverflow(value) { { // Chrome/Safari-specific fix: // When the textarea y-overflow is hidden, Chrome/Safari do not reflow the text to account for the space // made available by removing the scrollbar. The following forces the necessary text reflow. var width = ta.style.width; ta.style.width = '0px'; // Force reflow: /* jshint ignore:start */ ta.offsetWidth; /* jshint ignore:end */ ta.style.width = width; } ta.style.overflowY = value; } function getParentOverflows(el) { var arr = []; while (el && el.parentNode && el.parentNode instanceof Element) { if (el.parentNode.scrollTop) { arr.push({ node: el.parentNode, scrollTop: el.parentNode.scrollTop }); } el = el.parentNode; } return arr; } function resize() { var originalHeight = ta.style.height; var overflows = getParentOverflows(ta); var docTop = document.documentElement && document.documentElement.scrollTop; // Needed for Mobile IE (ticket #240) ta.style.height = 'auto'; var endHeight = ta.scrollHeight + heightOffset; if (ta.scrollHeight === 0) { // If the scrollHeight is 0, then the element probably has display:none or is detached from the DOM. ta.style.height = originalHeight; return; } ta.style.height = endHeight + 'px'; // used to check if an update is actually necessary on window.resize clientWidth = ta.clientWidth; // prevents scroll-position jumping overflows.forEach(function (el) { el.node.scrollTop = el.scrollTop; }); if (docTop) { document.documentElement.scrollTop = docTop; } } function update() { resize(); var styleHeight = Math.round(parseFloat(ta.style.height)); var computed = window.getComputedStyle(ta, null); var actualHeight = Math.round(parseFloat(computed.height)); // The actual height not matching the style height (set via the resize method) indicates that // the max-height has been exceeded, in which case the overflow should be set to visible. if (actualHeight !== styleHeight) { if (computed.overflowY !== 'visible') { changeOverflow('visible'); resize(); actualHeight = Math.round(parseFloat(window.getComputedStyle(ta, null).height)); } } else { // Normally keep overflow set to hidden, to avoid flash of scrollbar as the textarea expands. if (computed.overflowY !== 'hidden') { changeOverflow('hidden'); resize(); actualHeight = Math.round(parseFloat(window.getComputedStyle(ta, null).height)); } } if (cachedHeight !== actualHeight) { cachedHeight = actualHeight; var evt = createEvent('autosize:resized'); try { ta.dispatchEvent(evt); } catch (err) { // Firefox will throw an error on dispatchEvent for a detached element // https://bugzilla.mozilla.org/show_bug.cgi?id=889376 } } } var pageResize = function pageResize() { if (ta.clientWidth !== clientWidth) { update(); } }; var destroy = (function (style) { window.removeEventListener('resize', pageResize, false); ta.removeEventListener('input', update, false); ta.removeEventListener('keyup', update, false); ta.removeEventListener('autosize:destroy', destroy, false); ta.removeEventListener('autosize:update', update, false); Object.keys(style).forEach(function (key) { ta.style[key] = style[key]; }); map['delete'](ta); }).bind(ta, { height: ta.style.height, resize: ta.style.resize, overflowY: ta.style.overflowY, overflowX: ta.style.overflowX, wordWrap: ta.style.wordWrap }); ta.addEventListener('autosize:destroy', destroy, false); // IE9 does not fire onpropertychange or oninput for deletions, // so binding to onkeyup to catch most of those events. // There is no way that I know of to detect something like 'cut' in IE9. if ('onpropertychange' in ta && 'oninput' in ta) { ta.addEventListener('keyup', update, false); } window.addEventListener('resize', pageResize, false); ta.addEventListener('input', update, false); ta.addEventListener('autosize:update', update, false); ta.style.overflowX = 'hidden'; ta.style.wordWrap = 'break-word'; map.set(ta, { destroy: destroy, update: update }); init(); } function destroy(ta) { var methods = map.get(ta); if (methods) { methods.destroy(); } } function update(ta) { var methods = map.get(ta); if (methods) { methods.update(); } } var autosize = null; // Do nothing in Node.js environment and IE8 (or lower) if (typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') { autosize = function (el) { return el; }; autosize.destroy = function (el) { return el; }; autosize.update = function (el) { return el; }; } else { autosize = function (el, options) { if (el) { Array.prototype.forEach.call(el.length ? el : [el], function (x) { return assign(x, options); }); } return el; }; autosize.destroy = function (el) { if (el) { Array.prototype.forEach.call(el.length ? el : [el], destroy); } return el; }; autosize.update = function (el) { if (el) { Array.prototype.forEach.call(el.length ? el : [el], update); } return el; }; } module.exports = autosize; }); /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('textarea', { staticClass: "md-input", attrs: { "disabled": _vm.disabled, "required": _vm.required, "placeholder": _vm.placeholder, "maxlength": _vm.maxlength }, domProps: { "value": _vm.value }, on: { "focus": _vm.onFocus, "blur": _vm.onBlur, "input": _vm.onInput } }) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-62d24f30", module.exports) } } /***/ }, /* 133 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-input-container.md-input-invalid:after {\n background-color: WARN-COLOR; }\n\n.THEME_NAME.md-input-container.md-input-invalid label,\n.THEME_NAME.md-input-container.md-input-invalid .md-error,\n.THEME_NAME.md-input-container.md-input-invalid .md-count,\n.THEME_NAME.md-input-container.md-input-invalid input,\n.THEME_NAME.md-input-container.md-input-invalid textarea {\n color: WARN-COLOR; }\n\n.THEME_NAME.md-input-container.md-input-focused.md-input-inline label {\n color: rgba(0, 0, 0, 0.54); }\n\n.THEME_NAME.md-input-container.md-input-focused.md-input-required label:after {\n color: WARN-COLOR; }\n\n.THEME_NAME.md-input-container.md-input-focused:after {\n height: 2px;\n background-color: PRIMARY-COLOR; }\n\n.THEME_NAME.md-input-container.md-input-focused input,\n.THEME_NAME.md-input-container.md-input-focused textarea {\n color: PRIMARY-COLOR;\n text-shadow: 0 0 0 BACKGROUND-CONTRAST;\n -webkit-text-fill-color: transparent; }\n\n.THEME_NAME.md-input-container.md-input-focused label {\n color: PRIMARY-COLOR; }\n" /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdLayout = __webpack_require__(135); var _mdLayout2 = _interopRequireDefault(_mdLayout); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-layout', Vue.extend(_mdLayout2.default)); } module.exports = exports['default']; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(136) /* script */ __vue_exports__ = __webpack_require__(137) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdLayout/mdLayout.vue" /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-1f1a95a6", __vue_options__) } else { hotAPI.reload("data-v-1f1a95a6", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdLayout.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 136 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 137 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // exports.default = { props: { mdTag: { type: String, default: 'div' }, mdRow: Boolean, mdRowXsmall: Boolean, mdRowSmall: Boolean, mdRowMedium: Boolean, mdRowLarge: Boolean, mdRowXlarge: Boolean, mdColumn: Boolean, mdColumnXsmall: Boolean, mdColumnSmall: Boolean, mdColumnMedium: Boolean, mdColumnLarge: Boolean, mdColumnXlarge: Boolean, mdHideXsmall: Boolean, mdHideSmall: Boolean, mdHideMedium: Boolean, mdHideLarge: Boolean, mdHideXlarge: Boolean, mdGutter: [String, Number, Boolean], mdFlex: [String, Number, Boolean], mdFlexXsmall: [String, Number, Boolean], mdFlexSmall: [String, Number, Boolean], mdFlexMedium: [String, Number, Boolean], mdFlexLarge: [String, Number, Boolean], mdFlexXlarge: [String, Number, Boolean], mdFlexOffset: [String, Number] }, computed: { classes: function classes() { var classes = { 'md-row': this.mdRow, 'md-row-xsmall': this.mdRowXsmall, 'md-row-small': this.mdRowSmall, 'md-row-medium': this.mdRowMedium, 'md-row-large': this.mdRowLarge, 'md-row-xlarge': this.mdRowXlarge, 'md-column': this.mdColumn, 'md-column-xsmall': this.mdColumnXsmall, 'md-column-small': this.mdColumnSmall, 'md-column-medium': this.mdColumnMedium, 'md-column-large': this.mdColumnLarge, 'md-column-xlarge': this.mdColumnXlarge, 'md-hide-xsmall': this.mdHideXsmall, 'md-hide-small': this.mdHideSmall, 'md-hide-medium': this.mdHideMedium, 'md-hide-large': this.mdHideLarge, 'md-hide-xlarge': this.mdHideXlarge }; if (this.mdGutter) { if (typeof this.mdGutter === 'boolean') { classes['md-gutter'] = true; } else if (this.mdGutter) { classes['md-gutter-' + this.mdGutter] = true; } } if (this.mdFlexOffset) { classes['md-flex-offset-' + this.mdFlexOffset] = true; } this.generateFlexClasses('', 'mdFlex', classes); this.generateFlexClasses('xsmall', 'mdFlexXsmall', classes); this.generateFlexClasses('small', 'mdFlexSmall', classes); this.generateFlexClasses('medium', 'mdFlexMedium', classes); this.generateFlexClasses('large', 'mdFlexLarge', classes); this.generateFlexClasses('xlarge', 'mdFlexXlarge', classes); return classes; } }, methods: { generateFlexClasses: function generateFlexClasses(size, name, object) { if (size) { size = '-' + size; } if (this[name]) { if (typeof this[name] === 'boolean') { object['md-flex' + size] = true; } else { object['md-flex' + size + '-' + this[name]] = true; } } } }, render: function render(createElement) { return createElement(this.mdTag, { staticClass: 'md-layout', class: this.classes }, this.$slots.default); } }; module.exports = exports['default']; /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdList = __webpack_require__(139); var _mdList2 = _interopRequireDefault(_mdList); var _mdListItem = __webpack_require__(143); var _mdListItem2 = _interopRequireDefault(_mdListItem); var _mdListExpand = __webpack_require__(145); var _mdListExpand2 = _interopRequireDefault(_mdListExpand); var _mdList3 = __webpack_require__(148); var _mdList4 = _interopRequireDefault(_mdList3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-list', Vue.extend(_mdList2.default)); Vue.component('md-list-item', Vue.extend(_mdListItem2.default)); Vue.component('md-list-expand', Vue.extend(_mdListExpand2.default)); Vue.material.styles.push(_mdList4.default); } module.exports = exports['default']; /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(140) /* script */ __vue_exports__ = __webpack_require__(141) /* template */ var __vue_template__ = __webpack_require__(142) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdList/mdList.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-426a192d", __vue_options__) } else { hotAPI.reload("data-v-426a192d", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdList.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 140 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { mixins: [_mixin2.default] }; // // // // // // // // module.exports = exports['default']; /***/ }, /* 142 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('ul', { staticClass: "md-list", class: [_vm.themeClass] }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-426a192d", module.exports) } } /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(144) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdList/mdListItem.vue" /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-5f463740", __vue_options__) } else { hotAPI.reload("data-v-5f463740", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdListItem.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 144 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); 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); } } exports.default = { props: { href: String, target: String, disabled: Boolean }, render: function render(createElement) { var _this = this; var containerClass = 'md-button md-list-item-container'; var holderClass = 'md-list-item-holder'; var slot = this.$slots.default; var componentOptions = slot[0].componentOptions; var expandSlot = void 0; var expandSlotIndex = void 0; var listItemSpec = { staticClass: 'md-list-item', on: { click: function click($event) { _this.$emit('click', $event); } } }; var createItemHolder = function createItemHolder(content) { return createElement('div', { staticClass: holderClass }, content); }; var createRipple = function createRipple() { return createElement('md-ink-ripple'); }; var createCompatibleRouterLink = function createCompatibleRouterLink() { slot[0].data.staticClass = containerClass + ' ' + holderClass; return createElement('li', listItemSpec, [].concat(_toConsumableArray(slot), [createRipple()])); }; var prepareExpandList = function prepareExpandList() { slot.some(function (slot, index) { if (slot.componentOptions && slot.componentOptions.tag === 'md-list-expand') { expandSlot = slot; expandSlotIndex = index; return true; } }); }; var createExpandIndicator = function createExpandIndicator() { return createElement('md-icon', { staticClass: 'md-list-expand-indicator' }, 'keyboard_arrow_down'); }; var recalculateExpand = function recalculateExpand(element) { element.$children.some(function (expand) { if (expand.$el.classList.contains('md-list-expand')) { expand.calculatePadding(); } }); }; var handleExpandClick = function handleExpandClick(scope) { var target = void 0; scope.$parent.$children.some(function (child) { var classList = child.$el.classList; if (classList.contains('md-list-item-expand') && classList.contains('md-active')) { target = child; classList.remove('md-active'); recalculateExpand(child); return true; } }); if (!target || scope.$el !== target.$el) { scope.$el.classList.add('md-active'); } }; var createExpandElement = function createExpandElement() { slot.splice(expandSlotIndex, 1); slot.push(createExpandIndicator()); return createElement('button', { staticClass: containerClass, on: { click: function click() { handleExpandClick(_this); _this.$emit('click'); } } }, [createItemHolder(slot), createRipple()]); }; var createExpandList = function createExpandList() { listItemSpec.staticClass += ' md-list-item-expand'; return createElement('li', listItemSpec, [createExpandElement(), expandSlot]); }; if (componentOptions && componentOptions.tag === 'router-link') { return createCompatibleRouterLink(); } prepareExpandList(); if (expandSlot) { return createExpandList(); } var buttonSpec = createElement('md-button', { staticClass: containerClass, attrs: { target: this.target, href: this.href, disabled: this.disabled } }, [createItemHolder(slot)]); if (this.target) { buttonSpec.data.attrs.rel = 'noopener'; } return createElement('li', listItemSpec, [buttonSpec]); } }; module.exports = exports['default']; /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(146) /* template */ var __vue_template__ = __webpack_require__(147) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdList/mdListExpand.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-149bf327", __vue_options__) } else { hotAPI.reload("data-v-149bf327", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdListExpand.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 146 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // exports.default = { data: function data() { return { height: 0 }; }, methods: { calculatePadding: function calculatePadding() { this.height = -this.$el.offsetHeight + 'px'; } }, mounted: function mounted() { this.calculatePadding(); } }; module.exports = exports['default']; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-list-expand", style: ({ 'margin-bottom': _vm.height }) }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-149bf327", module.exports) } } /***/ }, /* 148 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-list {\n background-color: BACKGROUND-COLOR-A100;\n color: BACKGROUND-CONTRAST; }\n .THEME_NAME.md-list.md-transparent {\n background-color: transparent;\n color: inherit; }\n .THEME_NAME.md-list .md-list-item .router-link-active.md-list-item-container {\n color: PRIMARY-COLOR; }\n .THEME_NAME.md-list .md-list-item .router-link-active.md-list-item-container > .md-icon {\n color: PRIMARY-COLOR; }\n .THEME_NAME.md-list .md-list-item.md-primary .md-list-item-container {\n color: PRIMARY-COLOR; }\n .THEME_NAME.md-list .md-list-item.md-primary .md-list-item-container > .md-icon {\n color: PRIMARY-COLOR; }\n .THEME_NAME.md-list .md-list-item.md-accent .md-list-item-container {\n color: ACCENT-COLOR; }\n .THEME_NAME.md-list .md-list-item.md-accent .md-list-item-container > .md-icon {\n color: ACCENT-COLOR; }\n .THEME_NAME.md-list .md-list-item.md-warn .md-list-item-container {\n color: WARN-COLOR; }\n .THEME_NAME.md-list .md-list-item.md-warn .md-list-item-container > .md-icon {\n color: WARN-COLOR; }\n .THEME_NAME.md-list .md-list-item-expand .md-list-item-container {\n background-color: BACKGROUND-COLOR-A100; }\n .THEME_NAME.md-list .md-list-item-expand .md-list-item-container:hover, .THEME_NAME.md-list .md-list-item-expand .md-list-item-container:focus {\n background-color: rgba(153, 153, 153, 0.2); }\n" /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdMenu = __webpack_require__(150); var _mdMenu2 = _interopRequireDefault(_mdMenu); var _mdMenuItem = __webpack_require__(155); var _mdMenuItem2 = _interopRequireDefault(_mdMenuItem); var _mdMenuContent = __webpack_require__(159); var _mdMenuContent2 = _interopRequireDefault(_mdMenuContent); var _mdMenu3 = __webpack_require__(162); var _mdMenu4 = _interopRequireDefault(_mdMenu3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-menu', Vue.extend(_mdMenu2.default)); Vue.component('md-menu-item', Vue.extend(_mdMenuItem2.default)); Vue.component('md-menu-content', Vue.extend(_mdMenuContent2.default)); Vue.material.styles.push(_mdMenu4.default); } module.exports = exports['default']; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(151) /* script */ __vue_exports__ = __webpack_require__(152) /* template */ var __vue_template__ = __webpack_require__(154) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdMenu/mdMenu.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-008203e6", __vue_options__) } else { hotAPI.reload("data-v-008203e6", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdMenu.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 151 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _transitionEndEventName = __webpack_require__(90); var _transitionEndEventName2 = _interopRequireDefault(_transitionEndEventName); var _getInViewPosition = __webpack_require__(153); var _getInViewPosition2 = _interopRequireDefault(_getInViewPosition); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // // // // // // // // // // exports.default = { props: { mdSize: { type: [Number, String], default: 0 }, mdDirection: { type: String, default: 'bottom right' }, mdAlignTrigger: { type: Boolean, default: false }, mdOffsetX: { type: [Number, String], default: 0 }, mdOffsetY: { type: [Number, String], default: 0 }, mdCloseOnSelect: { type: Boolean, default: true } }, data: function data() { return { active: false }; }, watch: { mdSize: function mdSize(current, previous) { if (current >= 1 && current <= 7) { this.removeLastSizeMenuContentClass(previous); this.addNewSizeMenuContentClass(current); } }, mdDirection: function mdDirection(current, previous) { this.removeLastDirectionMenuContentClass(previous); this.addNewDirectionMenuContentClass(current); }, mdAlignTrigger: function mdAlignTrigger(trigger) { this.handleAlignTriggerClass(trigger); } }, methods: { validateMenu: function validateMenu() { if (!this.menuContent) { this.$destroy(); throw new Error('You must have a md-menu-content inside your menu.'); } if (!this.menuTrigger) { this.$destroy(); throw new Error('You must have an element with a md-menu-trigger attribute inside your menu.'); } }, removeLastSizeMenuContentClass: function removeLastSizeMenuContentClass(size) { this.menuContent.classList.remove('md-size-' + size); }, removeLastDirectionMenuContentClass: function removeLastDirectionMenuContentClass(direction) { this.menuContent.classList.remove('md-direction-' + direction.replace(/ /g, '-')); }, addNewSizeMenuContentClass: function addNewSizeMenuContentClass(size) { this.menuContent.classList.add('md-size-' + size); }, addNewDirectionMenuContentClass: function addNewDirectionMenuContentClass(direction) { this.menuContent.classList.add('md-direction-' + direction.replace(/ /g, '-')); }, handleAlignTriggerClass: function handleAlignTriggerClass(trigger) { if (trigger) { this.menuContent.classList.add('md-align-trigger'); } }, getPosition: function getPosition(vertical, horizontal) { var menuTriggerRect = this.menuTrigger.getBoundingClientRect(); var top = vertical === 'top' ? menuTriggerRect.top + menuTriggerRect.height - this.menuContent.offsetHeight : menuTriggerRect.top; var left = horizontal === 'left' ? menuTriggerRect.left - this.menuContent.offsetWidth + menuTriggerRect.width : menuTriggerRect.left; top += parseInt(this.mdOffsetY, 10); left += parseInt(this.mdOffsetX, 10); if (this.mdAlignTrigger) { if (vertical === 'top') { top -= menuTriggerRect.height; } else { top += menuTriggerRect.height; } } return { top: top, left: left }; }, calculateMenuContentPos: function calculateMenuContentPos() { var position = void 0; if (!this.mdDirection) { position = this.getPosition('bottom', 'right'); } else { position = this.getPosition.apply(this, this.mdDirection.trim().split(' ')); } position = (0, _getInViewPosition2.default)(this.menuContent, position); this.menuContent.style.top = position.top + window.pageYOffset + 'px'; this.menuContent.style.left = position.left + window.pageXOffset + 'px'; }, recalculateOnResize: function recalculateOnResize() { window.requestAnimationFrame(this.calculateMenuContentPos); }, open: function open() { if (this.rootElement.contains(this.menuContent)) { this.rootElement.removeChild(this.menuContent); } this.rootElement.appendChild(this.menuContent); this.rootElement.appendChild(this.backdropElement); window.addEventListener('resize', this.recalculateOnResize); this.calculateMenuContentPos(); getComputedStyle(this.menuContent).top; this.menuContent.classList.add('md-active'); this.menuContent.focus(); this.active = true; this.$emit('open'); }, close: function close() { var _this = this; var close = function close(event) { if (_this.menuContent && event.target === _this.menuContent) { var activeRipple = _this.menuContent.querySelector('.md-ripple.md-active'); _this.menuContent.removeEventListener(_transitionEndEventName2.default, close); _this.menuTrigger.focus(); _this.active = false; if (activeRipple) { activeRipple.classList.remove('md-active'); } _this.rootElement.removeChild(_this.menuContent); _this.rootElement.removeChild(_this.backdropElement); window.removeEventListener('resize', _this.recalculateOnResize); } }; this.menuContent.addEventListener(_transitionEndEventName2.default, close); this.menuContent.classList.remove('md-active'); this.$emit('close'); }, toggle: function toggle() { if (this.active) { this.close(); } else { this.open(); } } }, mounted: function mounted() { var _this2 = this; this.$nextTick(function () { _this2.rootElement = _this2.$root.$el; _this2.menuTrigger = _this2.$el.querySelector('[md-menu-trigger]'); _this2.menuContent = _this2.$el.querySelector('.md-menu-content'); _this2.backdropElement = _this2.$refs.backdrop.$el; _this2.validateMenu(); _this2.handleAlignTriggerClass(_this2.mdAlignTrigger); _this2.addNewSizeMenuContentClass(_this2.mdSize); _this2.addNewDirectionMenuContentClass(_this2.mdDirection); _this2.$el.removeChild(_this2.$refs.backdrop.$el); _this2.menuContent.parentNode.removeChild(_this2.menuContent); _this2.menuTrigger.addEventListener('click', _this2.toggle); }); }, beforeDestroy: function beforeDestroy() { if (this.rootElement.contains(this.menuContent)) { this.rootElement.removeChild(this.menuContent); this.rootElement.removeChild(this.backdropElement); } this.menuTrigger.removeEventListener('click', this.toggle); window.removeEventListener('resize', this.recalculateOnResize); } }; module.exports = exports['default']; /***/ }, /* 153 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var margin = 8; var isAboveOfViewport = function isAboveOfViewport(element, position) { return position.top <= margin - parseInt(getComputedStyle(element).marginTop, 10); }; var isBelowOfViewport = function isBelowOfViewport(element, position) { return position.top + element.offsetHeight + margin >= window.innerHeight - parseInt(getComputedStyle(element).marginTop, 10); }; var isOnTheLeftOfViewport = function isOnTheLeftOfViewport(element, position) { return position.left <= margin - parseInt(getComputedStyle(element).marginLeft, 10); }; var isOnTheRightOfViewport = function isOnTheRightOfViewport(element, position) { return position.left + element.offsetWidth + margin >= window.innerWidth - parseInt(getComputedStyle(element).marginLeft, 10); }; var getInViewPosition = function getInViewPosition(element, position) { var computedStyle = getComputedStyle(element); if (isAboveOfViewport(element, position)) { position.top = margin - parseInt(computedStyle.marginTop, 10); } if (isOnTheLeftOfViewport(element, position)) { position.left = margin - parseInt(computedStyle.marginLeft, 10); } if (isOnTheRightOfViewport(element, position)) { position.left = window.innerWidth - margin - element.offsetWidth - parseInt(computedStyle.marginLeft, 10); } if (isBelowOfViewport(element, position)) { position.top = window.innerHeight - margin - element.offsetHeight - parseInt(computedStyle.marginTop, 10); } return position; }; exports.default = getInViewPosition; module.exports = exports["default"]; /***/ }, /* 154 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-menu" }, [_vm._t("default"), _vm._v(" "), _c('md-backdrop', { ref: "backdrop", staticClass: "md-menu-backdrop md-transparent md-active", on: { "close": _vm.close } })], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-008203e6", module.exports) } } /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(156) /* template */ var __vue_template__ = __webpack_require__(158) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdMenu/mdMenuItem.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-5cf45940", __vue_options__) } else { hotAPI.reload("data-v-5cf45940", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdMenuItem.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _getClosestVueParent = __webpack_require__(127); var _getClosestVueParent2 = _interopRequireDefault(_getClosestVueParent); __webpack_require__(157); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // // // // // // // // // // exports.default = { props: { disabled: Boolean }, data: function data() { return { parentContent: {}, index: 0 }; }, computed: { classes: function classes() { return { 'md-highlighted': this.highlighted }; }, highlighted: function highlighted() { if (this.index === this.parentContent.highlighted) { if (this.disabled) { if (this.parentContent.oldHighlight > this.parentContent.highlighted) { this.parentContent.highlighted--; } else { this.parentContent.highlighted++; } } if (this.index === 1) { this.parentContent.$el.scrollTop = 0; } else if (this.index === this.parentContent.itemsAmount) { this.parentContent.$el.scrollTop = this.parentContent.$el.scrollHeight; } else { this.$el.scrollIntoViewIfNeeded(false); } return true; } return false; } }, methods: { close: function close($event) { if (!this.disabled) { if (this.parentMenu.mdCloseOnSelect) { this.parentContent.close(); } this.$emit('click'); this.$emit('selected', $event); } } }, mounted: function mounted() { this.parentContent = (0, _getClosestVueParent2.default)(this.$parent, 'md-menu-content'); this.parentMenu = (0, _getClosestVueParent2.default)(this.$parent, 'md-menu'); if (!this.parentContent) { this.$destroy(); throw new Error('You must wrap the md-menu-item in a md-menu-content'); } this.parentContent.itemsAmount++; this.index = this.parentContent.itemsAmount; } }; module.exports = exports['default']; /***/ }, /* 157 */ /***/ function(module, exports) { if (!Element.prototype.scrollIntoViewIfNeeded) { Element.prototype.scrollIntoViewIfNeeded = function (centerIfNeeded) { centerIfNeeded = arguments.length === 0 ? true : !!centerIfNeeded; var parent = this.parentNode, parentComputedStyle = window.getComputedStyle(parent, null), parentBorderTopWidth = parseInt(parentComputedStyle.getPropertyValue('border-top-width')), parentBorderLeftWidth = parseInt(parentComputedStyle.getPropertyValue('border-left-width')), overTop = this.offsetTop - parent.offsetTop < parent.scrollTop, overBottom = (this.offsetTop - parent.offsetTop + this.clientHeight - parentBorderTopWidth) > (parent.scrollTop + parent.clientHeight), overLeft = this.offsetLeft - parent.offsetLeft < parent.scrollLeft, overRight = (this.offsetLeft - parent.offsetLeft + this.clientWidth - parentBorderLeftWidth) > (parent.scrollLeft + parent.clientWidth), alignWithTop = overTop && !overBottom; if ((overTop || overBottom) && centerIfNeeded) { parent.scrollTop = this.offsetTop - parent.offsetTop - parent.clientHeight / 2 - parentBorderTopWidth + this.clientHeight / 2; } if ((overLeft || overRight) && centerIfNeeded) { parent.scrollLeft = this.offsetLeft - parent.offsetLeft - parent.clientWidth / 2 - parentBorderLeftWidth + this.clientWidth / 2; } if ((overTop || overBottom || overLeft || overRight) && !centerIfNeeded) { this.scrollIntoView(alignWithTop); } }; } /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('md-list-item', { staticClass: "md-menu-item", class: _vm.classes, attrs: { "disabled": _vm.disabled }, on: { "click": _vm.close } }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-5cf45940", module.exports) } } /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(160) /* template */ var __vue_template__ = __webpack_require__(161) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdMenu/mdMenuContent.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-518d815c", __vue_options__) } else { hotAPI.reload("data-v-518d815c", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdMenuContent.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { data: function data() { return { oldHighlight: false, highlighted: false, itemsAmount: 0 }; }, mixins: [_mixin2.default], methods: { close: function close() { this.highlighted = false; this.$parent.close(); }, highlightItem: function highlightItem(direction) { this.oldHighlight = this.highlighted; if (direction === 'up') { if (this.highlighted === 1) { this.highlighted = this.itemsAmount; } else { this.highlighted--; } } if (direction === 'down') { if (this.highlighted === this.itemsAmount) { this.highlighted = 1; } else { this.highlighted++; } } }, fireClick: function fireClick() { if (this.highlighted > 0) { this.$children[0].$children[this.highlighted - 1].$el.click(); } } }, mounted: function mounted() { if (!this.$parent.$el.classList.contains('md-menu')) { this.$destroy(); throw new Error('You must wrap the md-menu-content in a md-menu'); } } }; // // // // // // // // // // // // // // // // // module.exports = exports['default']; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-menu-content", class: [_vm.themeClass], attrs: { "tabindex": "-1" }, on: { "keydown": [function($event) { if (_vm._k($event.keyCode, "esc", 27)) { return; } $event.preventDefault(); _vm.close($event) }, function($event) { if (_vm._k($event.keyCode, "tab", 9)) { return; } $event.preventDefault(); _vm.close($event) }, function($event) { if (_vm._k($event.keyCode, "up", 38)) { return; } $event.preventDefault(); _vm.highlightItem('up') }, function($event) { if (_vm._k($event.keyCode, "down", 40)) { return; } $event.preventDefault(); _vm.highlightItem('down') }, function($event) { if (_vm._k($event.keyCode, "enter", 13)) { return; } $event.preventDefault(); _vm.fireClick($event) }, function($event) { if (_vm._k($event.keyCode, "space", 32)) { return; } $event.preventDefault(); _vm.fireClick($event) }] } }, [_c('md-list', [_vm._t("default")], true)]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-518d815c", module.exports) } } /***/ }, /* 162 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-menu-content {\n background-color: BACKGROUND-COLOR-A100;\n color: BACKGROUND-CONTRAST; }\n .THEME_NAME.md-menu-content .md-menu-item:hover .md-button:not([disabled]), .THEME_NAME.md-menu-content .md-menu-item:focus .md-button:not([disabled]), .THEME_NAME.md-menu-content .md-menu-item.md-highlighted .md-button:not([disabled]) {\n background-color: BACKGROUND-CONTRAST-0.12; }\n .THEME_NAME.md-menu-content .md-menu-item[disabled] {\n color: BACKGROUND-CONTRAST-0.38; }\n" /***/ }, /* 163 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdRadio = __webpack_require__(164); var _mdRadio2 = _interopRequireDefault(_mdRadio); var _mdRadio3 = __webpack_require__(168); var _mdRadio4 = _interopRequireDefault(_mdRadio3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-radio', Vue.extend(_mdRadio2.default)); Vue.material.styles.push(_mdRadio4.default); } module.exports = exports['default']; /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(165) /* script */ __vue_exports__ = __webpack_require__(166) /* template */ var __vue_template__ = __webpack_require__(167) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdRadio/mdRadio.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-e87254d2", __vue_options__) } else { hotAPI.reload("data-v-e87254d2", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdRadio.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 165 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 166 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { props: { name: String, id: String, value: [String, Boolean, Number], mdValue: { type: [String, Boolean, Number], required: true }, disabled: Boolean }, mixins: [_mixin2.default], computed: { classes: function classes() { return { 'md-checked': this.value && this.mdValue.toString() === this.value.toString(), 'md-disabled': this.disabled }; } }, methods: { toggleCheck: function toggleCheck($event) { if (!this.disabled) { this.$emit('change', this.mdValue, $event); this.$emit('input', this.mdValue, $event); } } } }; // // // // // // // // // // // // // // module.exports = exports['default']; /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-radio", class: [_vm.themeClass, _vm.classes] }, [_c('div', { directives: [{ name: "md-ink-ripple", rawName: "v-md-ink-ripple", value: (_vm.disabled), expression: "disabled" }], staticClass: "md-radio-container", on: { "click": _vm.toggleCheck } }, [_c('input', { attrs: { "type": "radio", "name": _vm.name, "id": _vm.id, "disabled": _vm.disabled }, domProps: { "value": _vm.value } })]), _vm._v(" "), (_vm.$slots.default) ? _c('label', { staticClass: "md-radio-label", attrs: { "for": _vm.id || _vm.name } }, [_vm._t("default")], true) : _vm._e()]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-e87254d2", module.exports) } } /***/ }, /* 168 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-radio .md-radio-container:after {\n background-color: ACCENT-COLOR; }\n\n.THEME_NAME.md-radio.md-checked .md-radio-container {\n border-color: ACCENT-COLOR; }\n\n.THEME_NAME.md-radio.md-checked .md-ink-ripple {\n color: ACCENT-COLOR; }\n\n.THEME_NAME.md-radio.md-checked .md-ripple {\n opacity: .38; }\n\n.THEME_NAME.md-radio.md-primary .md-radio-container:after {\n background-color: PRIMARY-COLOR; }\n\n.THEME_NAME.md-radio.md-primary.md-checked .md-radio-container {\n border-color: PRIMARY-COLOR; }\n\n.THEME_NAME.md-radio.md-primary.md-checked .md-ink-ripple {\n color: PRIMARY-COLOR; }\n\n.THEME_NAME.md-radio.md-warn .md-radio-container:after {\n background-color: WARN-COLOR; }\n\n.THEME_NAME.md-radio.md-warn.md-checked .md-radio-container {\n border-color: WARN-COLOR; }\n\n.THEME_NAME.md-radio.md-warn.md-checked .md-ink-ripple {\n color: WARN-COLOR; }\n\n.THEME_NAME.md-radio.md-disabled .md-radio-container {\n border-color: rgba(0, 0, 0, 0.26); }\n .THEME_NAME.md-radio.md-disabled .md-radio-container:after {\n background-color: rgba(0, 0, 0, 0.26); }\n\n.THEME_NAME.md-radio.md-disabled.md-checked .md-radio-container {\n border-color: rgba(0, 0, 0, 0.26); }\n" /***/ }, /* 169 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdSelect = __webpack_require__(170); var _mdSelect2 = _interopRequireDefault(_mdSelect); var _mdOption = __webpack_require__(174); var _mdOption2 = _interopRequireDefault(_mdOption); var _mdSelect3 = __webpack_require__(177); var _mdSelect4 = _interopRequireDefault(_mdSelect3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-select', Vue.extend(_mdSelect2.default)); Vue.component('md-option', Vue.extend(_mdOption2.default)); Vue.material.styles.push(_mdSelect4.default); } module.exports = exports['default']; /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(171) /* script */ __vue_exports__ = __webpack_require__(172) /* template */ var __vue_template__ = __webpack_require__(173) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdSelect/mdSelect.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-1cdcfd26", __vue_options__) } else { hotAPI.reload("data-v-1cdcfd26", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdSelect.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 171 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 172 */ /***/ 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 && obj !== Symbol.prototype ? "symbol" : typeof obj; }; // // // // // // // // // // // // // // // // // // var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); var _getClosestVueParent = __webpack_require__(127); var _getClosestVueParent2 = _interopRequireDefault(_getClosestVueParent); var _isArray = __webpack_require__(122); var _isArray2 = _interopRequireDefault(_isArray); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { props: { name: String, id: String, required: Boolean, multiple: Boolean, value: [String, Number, Array], disabled: Boolean, placeholder: String, mdMenuClass: String }, mixins: [_mixin2.default], data: function data() { return { selectedValue: null, selectedText: null, multipleText: null, multipleOptions: {}, options: {}, optionsAmount: 0 }; }, computed: { classes: function classes() { return { 'md-disabled': this.disabled }; }, contentClasses: function contentClasses() { if (this.multiple) { return 'md-multiple ' + this.mdMenuClass; } return this.mdMenuClass; } }, watch: { value: function value(_value) { this.setTextAndValue(_value); }, disabled: function disabled() { this.setParentDisabled(); }, required: function required() { this.setParentRequired(); }, placeholder: function placeholder() { this.setParentPlaceholder(); } }, methods: { setParentDisabled: function setParentDisabled() { this.parentContainer.isDisabled = this.disabled; }, setParentRequired: function setParentRequired() { this.parentContainer.isRequired = this.required; }, setParentPlaceholder: function setParentPlaceholder() { this.parentContainer.hasPlaceholder = !!this.placeholder; }, getSingleValue: function getSingleValue(value) { var _this = this; var output = {}; Object.keys(this.options).forEach(function (index) { var options = _this.options[index]; if (options.value === value) { output.value = value; output.text = options.$refs.item.textContent; } }); return output; }, getMultipleValue: function getMultipleValue(modelValue) { var _this2 = this; if ((0, _isArray2.default)(this.value)) { var _ret = function () { var outputText = []; modelValue.forEach(function (value) { Object.keys(_this2.options).forEach(function (index) { var options = _this2.options[index]; if (options.value === value) { var text = options.$refs.item.textContent; _this2.multipleOptions[index] = { value: value, text: text }; outputText.push(text); } }); }); return { v: { value: modelValue, text: outputText.join(', ') } }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } return {}; }, setTextAndValue: function setTextAndValue(modelValue) { var output = this.multiple ? this.getMultipleValue(modelValue) : this.getSingleValue(modelValue); this.selectedValue = output.value; this.selectedText = output.text; if (this.selectedText && this.parentContainer) { this.parentContainer.setValue(this.selectedText); } }, changeValue: function changeValue(value) { this.$emit('input', value); this.$emit('change', value); }, selectMultiple: function selectMultiple(index, value, text) { var values = []; this.multipleOptions[index] = { value: value, text: text }; for (var key in this.multipleOptions) { if (this.multipleOptions.hasOwnProperty(key) && this.multipleOptions[key].value) { values.push(this.multipleOptions[key].value); } } this.changeValue(values); }, selectOption: function selectOption(value, text) { this.selectedText = text; this.setTextAndValue(value); this.changeValue(value); } }, mounted: function mounted() { this.parentContainer = (0, _getClosestVueParent2.default)(this.$parent, 'md-input-container'); if (this.parentContainer) { this.setParentDisabled(); this.setParentRequired(); this.setParentPlaceholder(); this.parentContainer.hasSelect = true; } this.setTextAndValue(this.value); }, beforeDestroy: function beforeDestroy() { if (this.parentContainer) { this.parentContainer.setValue(''); this.parentContainer.hasSelect = false; } } }; module.exports = exports['default']; /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-select", class: [_vm.themeClass, _vm.classes] }, [_c('md-menu', { attrs: { "md-close-on-select": !_vm.multiple } }, [_c('span', { ref: "value", staticClass: "md-select-value", attrs: { "md-menu-trigger": "" } }, [_vm._v(_vm._s(_vm.selectedText || _vm.multipleText || _vm.placeholder))]), _vm._v(" "), _c('md-menu-content', { staticClass: "md-select-content", class: [_vm.themeClass, _vm.contentClasses] }, [_vm._t("default")], true)]), _vm._v(" "), _c('select', { attrs: { "name": _vm.name, "id": _vm.id, "required": _vm.required, "disabled": _vm.disabled, "tabindex": "-1" } }, [_c('option', { domProps: { "value": _vm.value } }, [_vm._v(_vm._s(_vm.value))])])]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-1cdcfd26", module.exports) } } /***/ }, /* 174 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(175) /* template */ var __vue_template__ = __webpack_require__(176) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdSelect/mdOption.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-b3b71f34", __vue_options__) } else { hotAPI.reload("data-v-b3b71f34", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdOption.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _getClosestVueParent = __webpack_require__(127); var _getClosestVueParent2 = _interopRequireDefault(_getClosestVueParent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { props: { value: [String, Boolean, Number] }, data: function data() { return { parentSelect: {}, check: false, index: 0 }; }, computed: { isSelected: function isSelected() { if (this.value && this.parentSelect.value) { var thisValue = this.value.toString(); if (this.parentSelect.multiple) { return this.parentSelect.value.indexOf(thisValue) >= 0; } return this.value && this.parentSelect.value && thisValue === this.parentSelect.value.toString(); } return false; }, classes: function classes() { return { 'md-selected': this.isSelected, 'md-checked': this.check }; } }, methods: { setParentOption: function setParentOption() { if (!this.parentSelect.multiple) { this.parentSelect.selectOption(this.value, this.$refs.item.textContent); } else { this.check = !this.check; } }, selectOption: function selectOption($event) { this.setParentOption(); this.$emit('selected', $event); } }, watch: { isSelected: function isSelected(selected) { if (this.parentSelect.multiple) { this.check = selected; } }, check: function check(_check) { if (_check) { this.parentSelect.selectMultiple(this.index, this.value, this.$refs.item.textContent); } else { this.parentSelect.selectMultiple(this.index); } } }, mounted: function mounted() { this.parentSelect = (0, _getClosestVueParent2.default)(this.$parent, 'md-select'); this.parentContent = (0, _getClosestVueParent2.default)(this.$parent, 'md-menu-content'); if (!this.parentSelect) { throw new Error('You must wrap the md-option in a md-select'); } this.parentSelect.optionsAmount++; this.index = this.parentSelect.optionsAmount; this.parentSelect.multipleOptions[this.index] = {}; this.parentSelect.options[this.index] = this; if (this.parentSelect.value === this.value) { this.setParentOption(); } }, beforeDestroy: function beforeDestroy() { if (this.parentSelect) { delete this.parentSelect.options[this.index]; delete this.parentSelect.multipleOptions[this.index]; } } }; // // // // // // // // // // // // // // // // // // module.exports = exports['default']; /***/ }, /* 176 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('md-menu-item', { staticClass: "md-option", class: _vm.classes, attrs: { "tabindex": "-1" }, on: { "click": _vm.selectOption } }, [(_vm.parentSelect.multiple) ? _c('md-checkbox', { directives: [{ name: "model", rawName: "v-model", value: (_vm.check), expression: "check" }], staticClass: "md-primary", domProps: { "value": (_vm.check) }, on: { "input": function($event) { _vm.check = $event } } }, [_c('span', { ref: "item" }, [_vm._t("default")], true)]) : _c('span', { ref: "item" }, [_vm._t("default")], true), _vm._v(" ")]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-b3b71f34", module.exports) } } /***/ }, /* 177 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-select:after {\n color: BACKGROUND-CONTRAST-0.54; }\n\n.THEME_NAME.md-select:after {\n color: BACKGROUND-CONTRAST-0.38; }\n\n.THEME_NAME.md-select-content .md-menu-item.md-selected, .THEME_NAME.md-select-content .md-menu-item.md-checked {\n color: PRIMARY-COLOR; }\n" /***/ }, /* 178 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdSidenav = __webpack_require__(179); var _mdSidenav2 = _interopRequireDefault(_mdSidenav); var _mdSidenav3 = __webpack_require__(183); var _mdSidenav4 = _interopRequireDefault(_mdSidenav3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-sidenav', Vue.extend(_mdSidenav2.default)); Vue.material.styles.push(_mdSidenav4.default); } module.exports = exports['default']; /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(180) /* script */ __vue_exports__ = __webpack_require__(181) /* template */ var __vue_template__ = __webpack_require__(182) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdSidenav/mdSidenav.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-4904390e", __vue_options__) } else { hotAPI.reload("data-v-4904390e", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdSidenav.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 180 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { data: function data() { return { mdVisible: false }; }, mixins: [_mixin2.default], computed: { classes: function classes() { return this.mdVisible && 'md-active'; } }, methods: { show: function show() { this.mdVisible = true; this.$el.focus(); this.$emit('open'); }, close: function close() { this.mdVisible = false; this.$el.blur(); this.$emit('close'); }, toggle: function toggle() { if (this.mdVisible) { this.close(); } else { this.show(); } } } }; // // // // // // // // // // // // module.exports = exports['default']; /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-sidenav", class: [_vm.themeClass, _vm.classes], attrs: { "tabindex": "0" }, on: { "keyup": function($event) { if (_vm._k($event.keyCode, "esc", 27)) { return; } _vm.close($event) } } }, [_c('div', { staticClass: "md-sidenav-content" }, [_vm._t("default")], true), _vm._v(" "), _c('md-backdrop', { staticClass: "md-sidenav-backdrop", on: { "close": _vm.close } })]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-4904390e", module.exports) } } /***/ }, /* 183 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-sidenav .md-sidenav-content {\n background-color: BACKGROUND-COLOR-A100;\n color: BACKGROUND-CONTRAST; }\n" /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdSpinner = __webpack_require__(185); var _mdSpinner2 = _interopRequireDefault(_mdSpinner); var _mdSpinner3 = __webpack_require__(189); var _mdSpinner4 = _interopRequireDefault(_mdSpinner3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-spinner', Vue.extend(_mdSpinner2.default)); Vue.material.styles.push(_mdSpinner4.default); } module.exports = exports['default']; /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(186) /* script */ __vue_exports__ = __webpack_require__(187) /* template */ var __vue_template__ = __webpack_require__(188) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdSpinner/mdSpinner.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-7e174593", __vue_options__) } else { hotAPI.reload("data-v-7e174593", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdSpinner.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 186 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 187 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { props: { mdSize: { type: Number, default: 50 }, mdStroke: { type: Number, default: 3.5 }, mdIndeterminate: Boolean, mdProgress: { type: Number, default: 0 } }, mixins: [_mixin2.default], computed: { classes: function classes() { return { 'md-indeterminate': this.mdIndeterminate }; }, styles: function styles() { var newSize = this.mdSize + 'px'; return { width: newSize, height: newSize }; }, dashProgress: function dashProgress() { var progress = this.mdProgress * 125 / 100; if (this.mdIndeterminate) { return false; } if (progress >= 125) { progress = 130; } return progress + ', 200'; } }, data: function data() { return {}; }, methods: {} }; // // // // // // // // // // // // module.exports = exports['default']; /***/ }, /* 188 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('transition', { attrs: { "name": "md-spinner", "appear": "" } }, [_c('div', { staticClass: "md-spinner", class: [_vm.themeClass, _vm.classes], style: (_vm.styles) }, [_c('svg', { staticClass: "md-spinner-draw", attrs: { "viewBox": "25 25 50 50" } }, [_c('circle', { staticClass: "md-spinner-path", attrs: { "cx": "50", "cy": "50", "r": "20", "stroke-width": _vm.mdStroke, "stroke-dasharray": _vm.dashProgress } })])])]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-7e174593", module.exports) } } /***/ }, /* 189 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-spinner .md-spinner-path {\n stroke: PRIMARY-COLOR; }\n\n.THEME_NAME.md-spinner.md-accent .md-spinner-path {\n stroke: ACCENT-COLOR; }\n\n.THEME_NAME.md-spinner.md-warn .md-spinner-path {\n stroke: WARN-COLOR; }\n" /***/ }, /* 190 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdSubheader = __webpack_require__(191); var _mdSubheader2 = _interopRequireDefault(_mdSubheader); var _mdSubheader3 = __webpack_require__(195); var _mdSubheader4 = _interopRequireDefault(_mdSubheader3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-subheader', Vue.extend(_mdSubheader2.default)); Vue.material.styles.push(_mdSubheader4.default); } module.exports = exports['default']; /***/ }, /* 191 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(192) /* script */ __vue_exports__ = __webpack_require__(193) /* template */ var __vue_template__ = __webpack_require__(194) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdSubheader/mdSubheader.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-a2e7fe8a", __vue_options__) } else { hotAPI.reload("data-v-a2e7fe8a", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdSubheader.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 192 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 193 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { mixins: [_mixin2.default] }; // // // // // // // // // // // // module.exports = exports['default']; /***/ }, /* 194 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return (_vm.$parent.$options._componentTag === 'md-list') ? _c('li', { staticClass: "md-subheader", class: [_vm.themeClass] }, [_vm._t("default")], true) : _c('div', { staticClass: "md-subheader", class: [_vm.themeClass] }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-a2e7fe8a", module.exports) } } /***/ }, /* 195 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-subheader.md-primary {\n color: PRIMARY-COLOR; }\n\n.THEME_NAME.md-subheader.md-accent {\n color: ACCENT-COLOR; }\n\n.THEME_NAME.md-subheader.md-warn {\n color: WARN-COLOR; }\n" /***/ }, /* 196 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdSwitch = __webpack_require__(197); var _mdSwitch2 = _interopRequireDefault(_mdSwitch); var _mdSwitch3 = __webpack_require__(200); var _mdSwitch4 = _interopRequireDefault(_mdSwitch3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-switch', Vue.extend(_mdSwitch2.default)); Vue.material.styles.push(_mdSwitch4.default); } module.exports = exports['default']; /***/ }, /* 197 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(198) /* script */ __vue_exports__ = __webpack_require__(199) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdSwitch/mdSwitch.vue" /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-7e05ff26", __vue_options__) } else { hotAPI.reload("data-v-7e05ff26", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdSwitch.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 198 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 199 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var checkedPosition = 75; // // // // // // // // // // // // // // // // var initialPosition = '-1px'; exports.default = { props: { name: String, value: Boolean, id: String, disabled: Boolean, type: { type: String, default: 'button' } }, mixins: [_mixin2.default], data: function data() { return { leftPos: initialPosition, checked: this.value }; }, computed: { classes: function classes() { return { 'md-checked': Boolean(this.value), 'md-disabled': this.disabled }; }, styles: function styles() { return { transform: 'translate3D(' + this.leftPos + ', -50%, 0)' }; } }, watch: { checked: function checked() { this.setPosition(); }, value: function value(_value) { this.changeState(_value); } }, methods: { setPosition: function setPosition() { this.leftPos = this.checked ? checkedPosition + '%' : initialPosition; }, changeState: function changeState(checked, $event) { this.checked = checked; this.$emit('change', this.checked, $event); this.$emit('input', this.checked, $event); }, toggle: function toggle($event) { if (!this.disabled) { this.changeState(!this.checked, $event); } } }, mounted: function mounted() { this.$nextTick(this.setPosition); } }; module.exports = exports['default']; /***/ }, /* 200 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-switch.md-checked .md-switch-container {\n background-color: ACCENT-COLOR-500-0.5; }\n\n.THEME_NAME.md-switch.md-checked .md-switch-thumb {\n background-color: ACCENT-COLOR; }\n\n.THEME_NAME.md-switch.md-checked .md-ink-ripple {\n color: ACCENT-COLOR; }\n\n.THEME_NAME.md-switch.md-checked .md-ripple {\n opacity: .38; }\n\n.THEME_NAME.md-switch.md-checked.md-primary .md-switch-container {\n background-color: PRIMARY-COLOR-500-0.5; }\n\n.THEME_NAME.md-switch.md-checked.md-primary .md-switch-thumb {\n background-color: PRIMARY-COLOR; }\n\n.THEME_NAME.md-switch.md-checked.md-primary .md-ink-ripple {\n color: PRIMARY-COLOR; }\n\n.THEME_NAME.md-switch.md-checked.md-warn .md-switch-container {\n background-color: WARN-COLOR-500-0.5; }\n\n.THEME_NAME.md-switch.md-checked.md-warn .md-switch-thumb {\n background-color: WARN-COLOR; }\n\n.THEME_NAME.md-switch.md-checked.md-warn .md-ink-ripple {\n color: WARN-COLOR; }\n\n.THEME_NAME.md-switch.md-disabled .md-switch-container, .THEME_NAME.md-switch.md-disabled.md-checked .md-switch-container {\n background-color: rgba(0, 0, 0, 0.12); }\n\n.THEME_NAME.md-switch.md-disabled .md-switch-thumb, .THEME_NAME.md-switch.md-disabled.md-checked .md-switch-thumb {\n background-color: #bdbdbd; }\n" /***/ }, /* 201 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdTable = __webpack_require__(202); var _mdTable2 = _interopRequireDefault(_mdTable); var _mdTableRow = __webpack_require__(206); var _mdTableRow2 = _interopRequireDefault(_mdTableRow); var _mdTableHead = __webpack_require__(209); var _mdTableHead2 = _interopRequireDefault(_mdTableHead); var _mdTableCell = __webpack_require__(212); var _mdTableCell2 = _interopRequireDefault(_mdTableCell); var _mdTableEdit = __webpack_require__(215); var _mdTableEdit2 = _interopRequireDefault(_mdTableEdit); var _mdTableCard = __webpack_require__(218); var _mdTableCard2 = _interopRequireDefault(_mdTableCard); var _mdTableAlternateHeader = __webpack_require__(221); var _mdTableAlternateHeader2 = _interopRequireDefault(_mdTableAlternateHeader); var _mdTablePagination = __webpack_require__(224); var _mdTablePagination2 = _interopRequireDefault(_mdTablePagination); var _mdTable3 = __webpack_require__(227); var _mdTable4 = _interopRequireDefault(_mdTable3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-table', Vue.extend(_mdTable2.default)); Vue.component('md-table-header', { functional: true, render: function render(h, scope) { return h('thead', { staticClass: 'md-table-header' }, scope.children); } }); Vue.component('md-table-body', { functional: true, render: function render(h, scope) { return h('tbody', { staticClass: 'md-table-body' }, scope.children); } }); Vue.component('md-table-row', Vue.extend(_mdTableRow2.default)); Vue.component('md-table-head', Vue.extend(_mdTableHead2.default)); Vue.component('md-table-cell', Vue.extend(_mdTableCell2.default)); Vue.component('md-table-edit', Vue.extend(_mdTableEdit2.default)); Vue.component('md-table-card', Vue.extend(_mdTableCard2.default)); Vue.component('md-table-pagination', Vue.extend(_mdTablePagination2.default)); Vue.component('md-table-alternate-header', Vue.extend(_mdTableAlternateHeader2.default)); Vue.material.styles.push(_mdTable4.default); } module.exports = exports['default']; /***/ }, /* 202 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(203) /* script */ __vue_exports__ = __webpack_require__(204) /* template */ var __vue_template__ = __webpack_require__(205) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdTable/mdTable.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-dda64186", __vue_options__) } else { hotAPI.reload("data-v-dda64186", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdTable.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 203 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 204 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); var _getClosestVueParent = __webpack_require__(127); var _getClosestVueParent2 = _interopRequireDefault(_getClosestVueParent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // // // // // // // // // // exports.default = { props: { mdSortType: String, mdSort: String }, mixins: [_mixin2.default], data: function data() { return { sortType: this.mdSortType, sortBy: this.mdSort, hasRowSelection: false, data: [], numberOfRows: 0, numberOfSelected: 0, selectedRows: {} }; }, methods: { emitSort: function emitSort(name) { this.sortBy = name; this.$emit('sort', { name: name, type: this.sortType }); }, emitSelection: function emitSelection() { this.$emit('select', this.selectedRows); } }, mounted: function mounted() { this.parentCard = (0, _getClosestVueParent2.default)(this.$parent, 'md-table-card'); if (this.parentCard) { this.parentCard.tableInstance = this; } } }; module.exports = exports['default']; /***/ }, /* 205 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-table", class: [_vm.themeClass] }, [_c('table', [_vm._t("default")], true)]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-dda64186", module.exports) } } /***/ }, /* 206 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(207) /* template */ var __vue_template__ = __webpack_require__(208) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdTable/mdTableRow.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-cd7c46e6", __vue_options__) } else { hotAPI.reload("data-v-cd7c46e6", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdTableRow.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 207 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _getClosestVueParent = __webpack_require__(127); var _getClosestVueParent2 = _interopRequireDefault(_getClosestVueParent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var transitionClass = 'md-transition-off'; // // // // // // // // // // exports.default = { props: { mdAutoSelect: Boolean, mdSelection: Boolean, mdItem: Object }, data: function data() { return { parentTable: {}, headRow: false, checkbox: false, index: 0 }; }, computed: { isDisabled: function isDisabled() { return !this.mdSelection && !this.headRow; }, hasSelection: function hasSelection() { return this.mdSelection || this.headRow && this.parentTable.hasRowSelection; }, classes: function classes() { return { 'md-selected': this.checkbox }; } }, watch: { mdItem: function mdItem(newValue, oldValue) { this.parentTable.data[this.index] = this.mdItem; this.handleMultipleSelection(newValue === oldValue); } }, methods: { setSelectedRow: function setSelectedRow(value, index) { if (value) { this.parentTable.selectedRows[index] = this.parentTable.data[index]; ++this.parentTable.numberOfSelected; } else { delete this.parentTable.selectedRows[index]; --this.parentTable.numberOfSelected; } }, handleSingleSelection: function handleSingleSelection(value) { this.setSelectedRow(value, this.index - 1); this.parentTable.$children[0].checkbox = this.parentTable.numberOfSelected === this.parentTable.numberOfRows; }, handleMultipleSelection: function handleMultipleSelection(value) { var _this = this; if (this.parentTable.numberOfRows > 25) { this.parentTable.$el.classList.add(transitionClass); } this.parentTable.$children.forEach(function (row, index) { row.checkbox = value; if (!row.headRow) { _this.setSelectedRow(value, index - 1); } }); if (value) { this.parentTable.numberOfSelected = this.parentTable.numberOfRows; } else { this.parentTable.numberOfSelected = 0; } window.setTimeout(function () { return _this.parentTable.$el.classList.remove(transitionClass); }); }, select: function select(value) { if (this.hasSelection) { if (this.headRow) { this.handleMultipleSelection(value); } else { this.handleSingleSelection(value); } this.parentTable.emitSelection(); } }, autoSelect: function autoSelect() { if (this.mdAutoSelect && this.hasSelection) { this.checkbox = !this.checkbox; this.handleSingleSelection(this.checkbox); this.parentTable.emitSelection(); } } }, mounted: function mounted() { this.parentTable = (0, _getClosestVueParent2.default)(this.$parent, 'md-table'); if (this.$el.parentNode.tagName.toLowerCase() === 'thead') { this.headRow = true; } else { this.parentTable.numberOfRows++; this.index = this.parentTable.numberOfRows; if (this.mdSelection) { this.parentTable.hasRowSelection = true; } if (this.mdItem) { this.parentTable.data.push(this.mdItem); } } } }; module.exports = exports['default']; /***/ }, /* 208 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('tr', { staticClass: "md-table-row", class: _vm.classes, on: { "click": _vm.autoSelect } }, [(_vm.hasSelection) ? _c('md-table-cell', { staticClass: "md-table-selection" }, [_c('md-checkbox', { directives: [{ name: "model", rawName: "v-model", value: (_vm.checkbox), expression: "checkbox" }], attrs: { "disabled": _vm.isDisabled }, domProps: { "value": (_vm.checkbox) }, on: { "change": _vm.select, "input": function($event) { _vm.checkbox = $event } } })]) : _vm._e(), _vm._v(" "), _vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-cd7c46e6", module.exports) } } /***/ }, /* 209 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(210) /* template */ var __vue_template__ = __webpack_require__(211) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdTable/mdTableHead.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-4c7d46bd", __vue_options__) } else { hotAPI.reload("data-v-4c7d46bd", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdTableHead.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 210 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _getClosestVueParent = __webpack_require__(127); var _getClosestVueParent2 = _interopRequireDefault(_getClosestVueParent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { props: { mdNumeric: Boolean, mdSortBy: String, mdTooltip: String }, data: function data() { return { sortType: null, sorted: false, parentTable: {} }; }, computed: { classes: function classes() { var matchSort = this.hasMatchSort(); if (!matchSort) { this.sorted = false; } return { 'md-numeric': this.mdNumeric, 'md-sortable': this.mdSortBy, 'md-sorted': matchSort && this.sorted, 'md-sorted-descending': matchSort && this.sortType === 'desc' }; } }, methods: { hasMatchSort: function hasMatchSort() { return this.parentTable.sortBy === this.mdSortBy; }, changeSort: function changeSort() { if (this.mdSortBy) { if (this.sortType === 'asc' && this.sorted) { this.sortType = 'desc'; } else { this.sortType = 'asc'; } this.sorted = true; this.parentTable.sortType = this.sortType; this.parentTable.emitSort(this.mdSortBy); } } }, mounted: function mounted() { this.parentTable = (0, _getClosestVueParent2.default)(this.$parent, 'md-table'); if (this.hasMatchSort()) { this.sorted = true; this.sortType = this.parentTable.sortType; } } }; // // // // // // // // // // // // // // module.exports = exports['default']; /***/ }, /* 211 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('th', { staticClass: "md-table-head", class: _vm.classes, on: { "click": _vm.changeSort } }, [_c('div', { directives: [{ name: "md-ink-ripple", rawName: "v-md-ink-ripple", value: (!_vm.mdSortBy), expression: "!mdSortBy" }], staticClass: "md-table-head-container" }, [_c('div', { staticClass: "md-table-head-text md-test" }, [(_vm.mdSortBy) ? _c('md-icon', { staticClass: "md-sortable-icon" }, [_vm._v("arrow_downward")]) : _vm._e(), _vm._v(" "), _vm._t("default"), _vm._v(" "), (_vm.mdTooltip) ? _c('md-tooltip', [_vm._v(_vm._s(_vm.mdTooltip))]) : _vm._e()], true)])]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-4c7d46bd", module.exports) } } /***/ }, /* 212 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(213) /* template */ var __vue_template__ = __webpack_require__(214) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdTable/mdTableCell.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-584d713f", __vue_options__) } else { hotAPI.reload("data-v-584d713f", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdTableCell.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 213 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // // // exports.default = { props: { mdNumeric: Boolean }, data: function data() { return { hasAction: false }; }, computed: { classes: function classes() { return { 'md-numeric': this.mdNumeric, 'md-has-action': this.hasAction }; } }, mounted: function mounted() { if (this.$children.length > 0) { this.hasAction = true; } } }; module.exports = exports['default']; /***/ }, /* 214 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('td', { staticClass: "md-table-cell", class: _vm.classes }, [_c('div', { staticClass: "md-table-cell-container" }, [_vm._t("default")], true)]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-584d713f", module.exports) } } /***/ }, /* 215 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(216) /* template */ var __vue_template__ = __webpack_require__(217) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdTable/mdTableEdit.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-23087c32", __vue_options__) } else { hotAPI.reload("data-v-23087c32", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdTableEdit.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 216 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // // // // // // // // // // // // // // // // exports.default = { props: { value: [String, Number], mdLarge: Boolean, mdId: String, mdName: String, mdPlaceholder: String, mdMaxlength: [Number, String] }, data: function data() { return { active: false }; }, computed: { triggerClasses: function triggerClasses() { return { 'md-edited': this.value }; }, dialogClasses: function dialogClasses() { return { 'md-active': this.active, 'md-large': this.mdLarge }; }, realValue: function realValue() { console.log(this.value); } }, methods: { openDialog: function openDialog() { this.active = true; this.$refs.input.$el.focus(); document.addEventListener('click', this.closeDialogOnOffClick); }, closeDialog: function closeDialog() { if (this.active) { this.active = false; this.$refs.input.$el.blur(); document.removeEventListener('click', this.closeDialogOnOffClick); } }, closeDialogOnOffClick: function closeDialogOnOffClick(event) { if (!this.$refs.dialog.contains(event.target)) { this.closeDialog(); } }, confirmDialog: function confirmDialog() { var value = this.$refs.input.$el.value; this.closeDialog(); this.$emit('input', value); this.$emit('edited', value); } } }; module.exports = exports['default']; /***/ }, /* 217 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-table-edit", on: { "keydown": function($event) { if (_vm._k($event.keyCode, "esc", 27)) { return; } _vm.closeDialog($event) } } }, [_c('div', { staticClass: "md-table-edit-trigger", class: _vm.triggerClasses, on: { "click": function($event) { $event.stopPropagation(); _vm.openDialog($event) } } }, [_vm._v("\n " + _vm._s(_vm.value || _vm.mdPlaceholder) + "\n ")]), _vm._v(" "), _c('div', { ref: "dialog", staticClass: "md-table-dialog", class: _vm.dialogClasses }, [_c('md-input-container', [_c('md-input', { ref: "input", attrs: { "id": _vm.mdId, "name": _vm.mdName, "maxlength": _vm.mdMaxlength, "value": _vm.value, "placeholder": _vm.mdPlaceholder }, nativeOn: { "keydown": function($event) { if (_vm._k($event.keyCode, "enter", 13)) { return; } _vm.confirmDialog($event) } } })])])]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-23087c32", module.exports) } } /***/ }, /* 218 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(219) /* template */ var __vue_template__ = __webpack_require__(220) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdTable/mdTableCard.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-e2fe4826", __vue_options__) } else { hotAPI.reload("data-v-e2fe4826", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdTableCard.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 219 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { mixins: [_mixin2.default] }; // // // // // // module.exports = exports['default']; /***/ }, /* 220 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('md-card', { staticClass: "md-table-card", class: [_vm.themeClass] }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-e2fe4826", module.exports) } } /***/ }, /* 221 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(222) /* template */ var __vue_template__ = __webpack_require__(223) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdTable/mdTableAlternateHeader.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-1ea3ef5a", __vue_options__) } else { hotAPI.reload("data-v-1ea3ef5a", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdTableAlternateHeader.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 222 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); var _getClosestVueParent = __webpack_require__(127); var _getClosestVueParent2 = _interopRequireDefault(_getClosestVueParent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // // // // // // // // // // // // // exports.default = { props: { mdSelectedLabel: { type: String, default: 'selected' } }, mixins: [_mixin2.default], data: function data() { return { classes: {}, tableInstance: {} }; }, mounted: function mounted() { var _this = this; this.parentCard = (0, _getClosestVueParent2.default)(this.$parent, 'md-table-card'); this.$nextTick(function () { _this.tableInstance = _this.parentCard.tableInstance; _this.$watch('tableInstance.numberOfSelected', function () { _this.$refs.counter.textContent = _this.tableInstance.numberOfSelected; _this.classes = { 'md-active': _this.tableInstance.numberOfSelected > 0 }; }); }); } }; module.exports = exports['default']; /***/ }, /* 223 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-table-alternate-header", class: [_vm.themeClass, _vm.classes] }, [_c('md-toolbar', [_c('div', { staticClass: "md-counter" }, [_c('span', { ref: "counter" }, [_vm._v(_vm._s(_vm.tableInstance.numberOfSelected))]), _vm._v(" "), _c('span', [_vm._v(_vm._s(_vm.mdSelectedLabel))])]), _vm._v(" "), _vm._t("default")], true)]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-1ea3ef5a", module.exports) } } /***/ }, /* 224 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(225) /* template */ var __vue_template__ = __webpack_require__(226) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdTable/mdTablePagination.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-7f188892", __vue_options__) } else { hotAPI.reload("data-v-7f188892", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdTablePagination.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 225 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // // // // // // // // // // // // // // // exports.default = { props: { mdSize: { type: [Number, String], default: 10 }, mdPageOptions: [Array, Boolean], mdPage: { type: [Number, String], default: 1 }, mdTotal: { type: [Number, String], default: 'Many' }, mdLabel: { type: String, default: 'Rows per page' }, mdSeparator: { type: String, default: 'of' } }, data: function data() { return { subTotal: 0, currentSize: parseInt(this.mdSize, 10), currentPage: parseInt(this.mdPage, 10), totalItems: isNaN(this.mdTotal) ? Number.MAX_SAFE_INTEGER : parseInt(this.mdTotal, 10) }; }, computed: { lastPage: function lastPage() { return false; } }, methods: { emitPaginationEvent: function emitPaginationEvent() { if (this.canFireEvents) { var sub = this.currentPage * this.currentSize; this.subTotal = sub > this.mdTotal ? this.mdTotal : sub; this.$emit('pagination', { size: this.currentSize, page: this.currentPage }); } }, changeSize: function changeSize() { if (this.canFireEvents) { this.$emit('size', this.currentSize); this.emitPaginationEvent(); } }, previousPage: function previousPage() { if (this.canFireEvents) { this.currentPage--; this.$emit('page', this.currentPage); this.emitPaginationEvent(); } }, nextPage: function nextPage() { if (this.canFireEvents) { this.currentPage++; this.$emit('page', this.currentPage); this.emitPaginationEvent(); } } }, mounted: function mounted() { var _this = this; this.$nextTick(function () { _this.subTotal = _this.currentPage * _this.currentSize; _this.mdPageOptions = _this.mdPageOptions || [10, 25, 50, 100]; _this.currentSize = _this.mdPageOptions[0]; _this.canFireEvents = true; }); } }; module.exports = exports['default']; /***/ }, /* 226 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-table-pagination" }, [_c('span', { staticClass: "md-table-pagination-label" }, [_vm._v(_vm._s(_vm.mdLabel) + ":")]), _vm._v(" "), (_vm.mdPageOptions) ? _c('md-select', { directives: [{ name: "model", rawName: "v-model", value: (_vm.currentSize), expression: "currentSize" }], attrs: { "md-menu-class": "md-pagination-select" }, domProps: { "value": (_vm.currentSize) }, on: { "change": _vm.changeSize, "input": function($event) { _vm.currentSize = $event } } }, _vm._l((_vm.mdPageOptions), function(amount) { return _c('md-option', { attrs: { "value": amount } }, [_vm._v(_vm._s(amount))]) })) : _vm._e(), _vm._v(" "), _c('span', [_vm._v(_vm._s(((_vm.currentPage - 1) * _vm.currentSize) + 1) + "-" + _vm._s(_vm.subTotal) + " " + _vm._s(_vm.mdSeparator) + " " + _vm._s(_vm.mdTotal))]), _vm._v(" "), _c('md-button', { staticClass: "md-icon-button md-table-pagination-previous", attrs: { "disabled": _vm.currentPage === 1 }, on: { "click": _vm.previousPage } }, [_c('md-icon', [_vm._v("keyboard_arrow_left")])]), _vm._v(" "), _c('md-button', { staticClass: "md-icon-button md-table-pagination-next", attrs: { "disabled": _vm.currentSize * _vm.currentPage >= _vm.totalItems }, on: { "click": _vm.nextPage } }, [_c('md-icon', [_vm._v("keyboard_arrow_right")])])]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-7f188892", module.exports) } } /***/ }, /* 227 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-table-card .md-toolbar {\n background-color: BACKGROUND-COLOR-A100;\n color: BACKGROUND-CONTRAST-A100; }\n\n.THEME_NAME.md-table-alternate-header {\n background-color: BACKGROUND-COLOR-A100; }\n .THEME_NAME.md-table-alternate-header .md-toolbar {\n background-color: ACCENT-COLOR-A100-0.2;\n color: ACCENT-CONTRAST-A100; }\n .THEME_NAME.md-table-alternate-header .md-counter {\n color: ACCENT-COLOR; }\n" /***/ }, /* 228 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdTabs = __webpack_require__(229); var _mdTabs2 = _interopRequireDefault(_mdTabs); var _mdTab = __webpack_require__(233); var _mdTab2 = _interopRequireDefault(_mdTab); var _mdTabs3 = __webpack_require__(237); var _mdTabs4 = _interopRequireDefault(_mdTabs3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-tabs', Vue.extend(_mdTabs2.default)); Vue.component('md-tab', Vue.extend(_mdTab2.default)); Vue.material.styles.push(_mdTabs4.default); } module.exports = exports['default']; /***/ }, /* 229 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(230) /* script */ __vue_exports__ = __webpack_require__(231) /* template */ var __vue_template__ = __webpack_require__(232) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdTabs/mdTabs.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-c28dc5a6", __vue_options__) } else { hotAPI.reload("data-v-c28dc5a6", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdTabs.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 230 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 231 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { props: { mdFixed: Boolean, mdCentered: Boolean, mdRight: Boolean, mdDynamicHeight: { type: Boolean, default: true }, mdElevation: { type: [String, Number], default: 0 } }, mixins: [_mixin2.default], data: function data() { return { tabList: {}, activeTab: null, activeTabNumber: 0, hasIcons: false, hasLabel: false, transitionControl: null, contentHeight: '0px', contentWidth: '0px' }; }, computed: { tabClasses: function tabClasses() { return { 'md-dynamic-height': this.mdDynamicHeight, 'md-transition-off': this.transitionOff }; }, navigationClasses: function navigationClasses() { return { 'md-has-icon': this.hasIcons, 'md-has-label': this.hasLabel, 'md-fixed': this.mdFixed, 'md-right': !this.mdCentered && this.mdRight, 'md-centered': this.mdCentered || this.mdFixed }; }, indicatorClasses: function indicatorClasses() { var toLeft = this.lastIndicatorNumber > this.activeTabNumber; this.lastIndicatorNumber = this.activeTabNumber; return { 'md-transition-off': this.transitionOff, 'md-to-right': !toLeft, 'md-to-left': toLeft }; } }, methods: { getHeaderClass: function getHeaderClass(header) { return { 'md-active': this.activeTab === header.id, 'md-disabled': header.disabled }; }, registerTab: function registerTab(tabData) { this.tabList[tabData.id] = tabData; this.$forceUpdate(); }, unregisterTab: function unregisterTab(tabData) { delete this.tabList[tabData.id]; }, updateTab: function updateTab(tabData) { this.registerTab(tabData); if (tabData.active) { if (!tabData.disabled) { this.setActiveTab(tabData); } else { var tabsIds = Object.keys(this.tabList); var targetIndex = tabsIds.indexOf(tabData.id) + 1; var target = tabsIds[targetIndex]; if (target) { this.setActiveTab(this.tabList[target]); } else { this.setActiveTab(this.tabList[0]); } } } }, observeElementChanges: function observeElementChanges() { this.contentObserver = new MutationObserver(this.calculateOnWatch); this.navigationObserver = new MutationObserver(this.calculateOnWatch); this.contentObserver.observe(this.$refs.tabContent, { childList: true, attributes: true, characterData: true, subtree: true, attributeOldValue: true, characterDataOldValue: true }); this.navigationObserver.observe(this.$refs.tabNavigation.$el, { attributes: true }); }, getTabIndex: function getTabIndex(id) { var idList = Object.keys(this.tabList); return idList.indexOf(id); }, calculateIndicatorPos: function calculateIndicatorPos() { var tabsWidth = this.$el.offsetWidth; var activeTab = this.$refs.tabHeader[this.activeTabNumber]; var left = activeTab.offsetLeft; var right = tabsWidth - left - activeTab.offsetWidth; this.$refs.indicator.style.left = left + 'px'; this.$refs.indicator.style.right = right + 'px'; }, calculateTabsWidthAndPosition: function calculateTabsWidthAndPosition() { var width = this.$el.offsetWidth; this.contentWidth = width * this.activeTabNumber + 'px'; var index = 0; for (var tabId in this.tabList) { var tab = this.tabList[tabId]; tab.ref.width = width + 'px'; tab.ref.left = width * index + 'px'; index++; } }, calculateContentHeight: function calculateContentHeight() { var _this = this; this.$nextTick(function () { var height = _this.tabList[_this.activeTab].ref.$el.offsetHeight; _this.contentHeight = height + 'px'; }); }, calculatePosition: function calculatePosition() { var _this2 = this; window.requestAnimationFrame(function () { _this2.calculateIndicatorPos(); _this2.calculateTabsWidthAndPosition(); _this2.calculateContentHeight(); }); }, debounceTransition: function debounceTransition() { var _this3 = this; window.clearTimeout(this.transitionControl); this.transitionControl = window.setTimeout(function () { _this3.calculatePosition(); _this3.transitionOff = false; }, 200); }, calculateOnWatch: function calculateOnWatch() { this.transitionOff = true; this.calculatePosition(); this.debounceTransition(); }, setActiveTab: function setActiveTab(tabData) { this.hasIcons = !!tabData.icon; this.hasLabel = !!tabData.label; this.activeTab = tabData.id; this.activeTabNumber = this.getTabIndex(this.activeTab); this.calculatePosition(); this.$emit('change', this.activeTabNumber); } }, mounted: function mounted() { var _this4 = this; this.$nextTick(function () { _this4.observeElementChanges(); window.addEventListener('resize', _this4.calculateOnWatch); if (!_this4.activeTab) { var firstTab = Object.keys(_this4.tabList)[0]; _this4.setActiveTab(_this4.tabList[firstTab]); } }); }, beforeDestroy: function beforeDestroy() { if (this.contentObserver) { this.contentObserver.disconnect(); } if (this.navigationObserver) { this.navigationObserver.disconnect(); } window.removeEventListener('resize', this.calculateOnWatch); } }; // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // module.exports = exports['default']; /***/ }, /* 232 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-tabs", class: [_vm.themeClass, _vm.tabClasses] }, [_c('md-whiteframe', { ref: "tabNavigation", staticClass: "md-tabs-navigation", class: _vm.navigationClasses, attrs: { "md-tag": "nav", "md-elevation": _vm.mdElevation } }, [_vm._l((_vm.tabList), function(header) { return _c('button', { key: header.id, ref: "tabHeader", refInFor: true, staticClass: "md-tab-header", class: _vm.getHeaderClass(header), attrs: { "type": "button", "disabled": header.disabled }, on: { "click": function($event) { _vm.setActiveTab(header) } } }, [_c('md-ink-ripple', { attrs: { "md-disabled": header.disabled } }), _vm._v(" "), _c('div', { staticClass: "md-tab-header-container" }, [(header.icon) ? _c('md-icon', [_vm._v(_vm._s(header.icon))]) : _vm._e(), _vm._v(" "), (header.label) ? _c('span', [_vm._v(_vm._s(header.label))]) : _vm._e(), _vm._v(" "), (header.tooltip) ? _c('md-tooltip', { attrs: { "md-direction": header.tooltipDirection, "md-delay": header.tooltipDelay } }, [_vm._v(_vm._s(header.tooltip))]) : _vm._e()])]) }), _vm._v(" "), _c('span', { ref: "indicator", staticClass: "md-tab-indicator", class: _vm.indicatorClasses })], true), _vm._v(" "), _c('div', { ref: "tabContent", staticClass: "md-tabs-content", style: ({ height: _vm.contentHeight }) }, [_c('div', { staticClass: "md-tabs-wrapper", style: ({ transform: ("translate3D(-" + _vm.contentWidth + ", 0, 0)") }) }, [_vm._t("default")], true)])]) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-c28dc5a6", module.exports) } } /***/ }, /* 233 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* script */ __vue_exports__ = __webpack_require__(234) /* template */ var __vue_template__ = __webpack_require__(236) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdTabs/mdTab.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-8aa44a94", __vue_options__) } else { hotAPI.reload("data-v-8aa44a94", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdTab.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 234 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _uniqueId = __webpack_require__(235); var _uniqueId2 = _interopRequireDefault(_uniqueId); var _getClosestVueParent = __webpack_require__(127); var _getClosestVueParent2 = _interopRequireDefault(_getClosestVueParent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // // // // // // exports.default = { props: { id: [String, Number], mdLabel: [String, Number], mdIcon: String, mdActive: Boolean, mdDisabled: Boolean, mdTooltip: String, mdTooltipDelay: { type: String, default: '0' }, mdTooltipDirection: { type: String, default: 'bottom' } }, data: function data() { return { mounted: false, tabId: this.id || 'tab-' + (0, _uniqueId2.default)(), width: '0px', left: '0px' }; }, watch: { mdActive: function mdActive() { this.updateTabData(); }, mdDisabled: function mdDisabled() { this.updateTabData(); }, mdIcon: function mdIcon() { this.updateTabData(); }, mdLabel: function mdLabel() { this.updateTabData(); }, mdTooltip: function mdTooltip() { this.updateTabData(); }, mdTooltipDelay: function mdTooltipDelay() { this.updateTabData(); }, mdTooltipDirection: function mdTooltipDirection() { this.updateTabData(); } }, computed: { styles: function styles() { return { width: this.width, left: this.left }; } }, methods: { getTabData: function getTabData() { return { id: this.tabId, label: this.mdLabel, icon: this.mdIcon, active: this.mdActive, disabled: this.mdDisabled, tooltip: this.mdTooltip, tooltipDelay: this.mdTooltipDelay, tooltipDirection: this.mdTooltipDirection, ref: this }; }, updateTabData: function updateTabData() { this.parentTabs.updateTab(this.getTabData()); } }, mounted: function mounted() { var _this = this; this.parentTabs = (0, _getClosestVueParent2.default)(this.$parent, 'md-tabs'); if (!this.parentTabs) { throw new Error('You must wrap the md-tab in a md-tabs'); } this.$nextTick(function () { _this.mounted = true; _this.parentTabs.registerTab(_this.getTabData()); if (_this.mdActive) { _this.parentTabs.activeTab = _this.tabId; } }); }, beforeDestroy: function beforeDestroy() { this.parentTabs.unregisterTab(this.getTabData()); } }; module.exports = exports['default']; /***/ }, /* 235 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var uniqueId = function uniqueId() { return Math.random().toString(36).slice(4); }; exports.default = uniqueId; module.exports = exports["default"]; /***/ }, /* 236 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-tab", style: (_vm.styles), attrs: { "id": _vm.tabId } }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-8aa44a94", module.exports) } } /***/ }, /* 237 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-tabs > .md-tabs-navigation {\n background-color: PRIMARY-COLOR; }\n .THEME_NAME.md-tabs > .md-tabs-navigation .md-tab-header {\n color: PRIMARY-CONTRAST-0.54; }\n .THEME_NAME.md-tabs > .md-tabs-navigation .md-tab-header.md-active, .THEME_NAME.md-tabs > .md-tabs-navigation .md-tab-header:focus {\n color: PRIMARY-CONTRAST; }\n .THEME_NAME.md-tabs > .md-tabs-navigation .md-tab-header.md-disabled {\n color: PRIMARY-CONTRAST-0.26; }\n .THEME_NAME.md-tabs > .md-tabs-navigation .md-tab-indicator {\n background-color: ACCENT-COLOR; }\n\n.THEME_NAME.md-tabs.md-transparent > .md-tabs-navigation {\n background-color: transparent;\n border-bottom: 1px solid BACKGROUND-CONTRAST-0.12; }\n .THEME_NAME.md-tabs.md-transparent > .md-tabs-navigation .md-tab-header {\n color: BACKGROUND-CONTRAST-0.54; }\n .THEME_NAME.md-tabs.md-transparent > .md-tabs-navigation .md-tab-header.md-active, .THEME_NAME.md-tabs.md-transparent > .md-tabs-navigation .md-tab-header:focus {\n color: PRIMARY-COLOR; }\n .THEME_NAME.md-tabs.md-transparent > .md-tabs-navigation .md-tab-header.md-disabled {\n color: BACKGROUND-CONTRAST-0.26; }\n .THEME_NAME.md-tabs.md-transparent > .md-tabs-navigation .md-tab-indicator {\n background-color: PRIMARY-COLOR; }\n\n.THEME_NAME.md-tabs.md-accent > .md-tabs-navigation {\n background-color: ACCENT-COLOR; }\n .THEME_NAME.md-tabs.md-accent > .md-tabs-navigation .md-tab-header {\n color: ACCENT-CONTRAST-0.54; }\n .THEME_NAME.md-tabs.md-accent > .md-tabs-navigation .md-tab-header.md-active, .THEME_NAME.md-tabs.md-accent > .md-tabs-navigation .md-tab-header:focus {\n color: ACCENT-CONTRAST; }\n .THEME_NAME.md-tabs.md-accent > .md-tabs-navigation .md-tab-header.md-disabled {\n color: ACCENT-CONTRAST-0.26; }\n .THEME_NAME.md-tabs.md-accent > .md-tabs-navigation .md-tab-indicator {\n background-color: BACKGROUND-COLOR; }\n\n.THEME_NAME.md-tabs.md-warn > .md-tabs-navigation {\n background-color: WARN-COLOR; }\n .THEME_NAME.md-tabs.md-warn > .md-tabs-navigation .md-tab-header {\n color: WARN-CONTRAST-0.54; }\n .THEME_NAME.md-tabs.md-warn > .md-tabs-navigation .md-tab-header.md-active, .THEME_NAME.md-tabs.md-warn > .md-tabs-navigation .md-tab-header:focus {\n color: WARN-CONTRAST; }\n .THEME_NAME.md-tabs.md-warn > .md-tabs-navigation .md-tab-header.md-disabled {\n color: WARN-CONTRAST-0.26; }\n .THEME_NAME.md-tabs.md-warn > .md-tabs-navigation .md-tab-indicator {\n background-color: BACKGROUND-COLOR; }\n" /***/ }, /* 238 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdToolbar = __webpack_require__(239); var _mdToolbar2 = _interopRequireDefault(_mdToolbar); var _mdToolbar3 = __webpack_require__(243); var _mdToolbar4 = _interopRequireDefault(_mdToolbar3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-toolbar', Vue.extend(_mdToolbar2.default)); Vue.material.styles.push(_mdToolbar4.default); } module.exports = exports['default']; /***/ }, /* 239 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(240) /* script */ __vue_exports__ = __webpack_require__(241) /* template */ var __vue_template__ = __webpack_require__(242) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdToolbar/mdToolbar.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-668063d7", __vue_options__) } else { hotAPI.reload("data-v-668063d7", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdToolbar.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 240 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 241 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mixin = __webpack_require__(6); var _mixin2 = _interopRequireDefault(_mixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { mixins: [_mixin2.default] }; // // // // // // // // module.exports = exports['default']; /***/ }, /* 242 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('div', { staticClass: "md-toolbar", class: [_vm.themeClass] }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-668063d7", module.exports) } } /***/ }, /* 243 */ /***/ function(module, exports) { module.exports = ".THEME_NAME.md-toolbar {\n background-color: PRIMARY-COLOR;\n color: PRIMARY-CONTRAST; }\n .THEME_NAME.md-toolbar.md-accent {\n background-color: ACCENT-COLOR;\n color: ACCENT-CONTRAST; }\n .THEME_NAME.md-toolbar.md-warn {\n background-color: WARN-COLOR;\n color: WARN-CONTRAST; }\n .THEME_NAME.md-toolbar.md-transparent {\n background-color: transparent;\n color: BACKGROUND-CONTRAST; }\n" /***/ }, /* 244 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdTooltip = __webpack_require__(245); var _mdTooltip2 = _interopRequireDefault(_mdTooltip); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-tooltip', Vue.extend(_mdTooltip2.default)); } module.exports = exports['default']; /***/ }, /* 245 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(246) /* script */ __vue_exports__ = __webpack_require__(247) /* template */ var __vue_template__ = __webpack_require__(248) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdTooltip/mdTooltip.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-3104dae7", __vue_options__) } else { hotAPI.reload("data-v-3104dae7", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdTooltip.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 246 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 247 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _transitionEndEventName = __webpack_require__(90); var _transitionEndEventName2 = _interopRequireDefault(_transitionEndEventName); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } // // // // // // // // exports.default = { props: { mdDirection: { type: String, default: 'bottom' }, mdDelay: { type: String, default: '0' } }, data: function data() { return { active: false, parentClass: null, transitionOff: false, topPosition: false, leftPosition: false }; }, computed: { classes: function classes() { var cssClasses = { 'md-active': this.active, 'md-transition-off': this.transitionOff, 'md-tooltip-top': this.mdDirection === 'top', 'md-tooltip-right': this.mdDirection === 'right', 'md-tooltip-bottom': this.mdDirection === 'bottom', 'md-tooltip-left': this.mdDirection === 'left' }; if (this.parentClass) { cssClasses[this.parentClass] = true; } return cssClasses; }, style: function style() { return { 'transition-delay': this.mdDelay + 'ms', top: this.topPosition + 'px', left: this.leftPosition + 'px' }; } }, watch: { mdDirection: function mdDirection() { this.calculateTooltipPosition(); } }, methods: { removeTooltips: function removeTooltips() { var tooltips = [].concat(_toConsumableArray(this.rootElement.querySelectorAll('.md-tooltip'))); tooltips.forEach(function (tooltip) { if (tooltip.parentNode) { tooltip.parentNode.removeChild(tooltip); } }); this.tooltipElement.removeEventListener(_transitionEndEventName2.default, this.removeTooltips); }, calculateTooltipPosition: function calculateTooltipPosition() { var position = this.parentElement.getBoundingClientRect(); var cssPosition = {}; switch (this.mdDirection) { case 'top': cssPosition.top = position.top - this.$el.offsetHeight; cssPosition.left = position.left + position.width / 2; break; case 'right': cssPosition.top = position.top; cssPosition.left = position.left + position.width; break; case 'bottom': cssPosition.top = position.bottom; cssPosition.left = position.left + position.width / 2; break; case 'left': cssPosition.top = position.top; cssPosition.left = position.left - this.$el.offsetWidth; break; default: console.warn('Invalid ' + this.mdDirection + ' option to md-direction option'); } this.topPosition = cssPosition.top; this.leftPosition = cssPosition.left; }, generateTooltipClasses: function generateTooltipClasses() { var classes = []; [].concat(_toConsumableArray(this.parentElement.classList)).forEach(function (cssClass) { if (cssClass.indexOf('md-') >= 0 && cssClass !== 'md-active') { classes.push(cssClass + '-tooltip'); } }); this.parentClass = classes.join(' '); }, open: function open() { var _this = this; this.removeTooltips(); this.$nextTick(function () { _this.rootElement.appendChild(_this.tooltipElement); getComputedStyle(_this.tooltipElement).top; _this.transitionOff = true; _this.generateTooltipClasses(); _this.calculateTooltipPosition(); window.setTimeout(function () { _this.transitionOff = false; _this.active = true; }, 10); }); }, close: function close() { this.active = false; this.tooltipElement.removeEventListener(_transitionEndEventName2.default, this.removeTooltips); this.tooltipElement.addEventListener(_transitionEndEventName2.default, this.removeTooltips); } }, mounted: function mounted() { var _this2 = this; this.$nextTick(function () { _this2.tooltipElement = _this2.$el; _this2.parentElement = _this2.tooltipElement.parentNode; _this2.rootElement = _this2.$root.$el; _this2.$el.parentNode.removeChild(_this2.$el); _this2.parentElement.addEventListener('mouseenter', _this2.open); _this2.parentElement.addEventListener('focus', _this2.open); _this2.parentElement.addEventListener('mouseleave', _this2.close); _this2.parentElement.addEventListener('blur', _this2.close); }); }, beforeDestroy: function beforeDestroy() { this.active = false; this.removeTooltips(); if (this.parentElement) { this.parentElement.removeEventListener('mouseenter', this.open); this.parentElement.removeEventListener('focus', this.open); this.parentElement.removeEventListener('mouseleave', this.close); this.parentElement.removeEventListener('blur', this.close); } } }; module.exports = exports['default']; /***/ }, /* 248 */ /***/ function(module, exports, __webpack_require__) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._c; return _c('span', { staticClass: "md-tooltip", class: _vm.classes, style: (_vm.style) }, [_vm._t("default")], true) },staticRenderFns: []} module.exports.render._withStripped = true if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-3104dae7", module.exports) } } /***/ }, /* 249 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = install; var _mdWhiteframe = __webpack_require__(250); var _mdWhiteframe2 = _interopRequireDefault(_mdWhiteframe); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function install(Vue) { Vue.component('md-whiteframe', Vue.extend(_mdWhiteframe2.default)); } module.exports = exports['default']; /***/ }, /* 250 */ /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(251) /* script */ __vue_exports__ = __webpack_require__(252) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "/Users/marcosmoura/Projects/github/vue-material/src/components/mdWhiteframe/mdWhiteframe.vue" /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-01d6d326", __vue_options__) } else { hotAPI.reload("data-v-01d6d326", __vue_options__) } })()} if (__vue_options__.functional) {console.error("[vue-loader] mdWhiteframe.vue: functional components are not supported and should be defined in plain js files using render functions.")} module.exports = __vue_exports__ /***/ }, /* 251 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 252 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // // exports.default = { props: { mdElevation: { type: [String, Number], default: 1 }, mdTag: { type: String, default: 'div' } }, computed: { classes: function classes() { var numberedElevation = parseInt(this.mdElevation, 10); var elevationClass = 'md-whiteframe-'; if (!isNaN(numberedElevation) && typeof numberedElevation === 'number') { elevationClass += numberedElevation; elevationClass += 'dp'; } else if (this.mdElevation.indexOf('dp') > -1) { elevationClass += this.mdElevation; } return elevationClass; } }, render: function render(createElement) { return createElement(this.mdTag, { staticClass: 'md-whiteframe', class: this.classes }, this.$slots.default); } }; module.exports = exports['default']; /***/ }, /* 253 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _core = __webpack_require__(72); var _core2 = _interopRequireDefault(_core); var _mdAvatar = __webpack_require__(1); var _mdAvatar2 = _interopRequireDefault(_mdAvatar); var _mdBackdrop = __webpack_require__(11); var _mdBackdrop2 = _interopRequireDefault(_mdBackdrop); var _mdBottomBar = __webpack_require__(16); var _mdBottomBar2 = _interopRequireDefault(_mdBottomBar); var _mdButton = __webpack_require__(25); var _mdButton2 = _interopRequireDefault(_mdButton); var _mdButtonToggle = __webpack_require__(31); var _mdButtonToggle2 = _interopRequireDefault(_mdButtonToggle); var _mdCard = __webpack_require__(37); var _mdCard2 = _interopRequireDefault(_mdCard); var _mdCheckbox = __webpack_require__(66); var _mdCheckbox2 = _interopRequireDefault(_mdCheckbox); var _mdDialog = __webpack_require__(86); var _mdDialog2 = _interopRequireDefault(_mdDialog); var _mdDivider = __webpack_require__(108); var _mdDivider2 = _interopRequireDefault(_mdDivider); var _mdIcon = __webpack_require__(112); var _mdIcon2 = _interopRequireDefault(_mdIcon); var _mdInputContainer = __webpack_require__(118); var _mdInputContainer2 = _interopRequireDefault(_mdInputContainer); var _mdLayout = __webpack_require__(134); var _mdLayout2 = _interopRequireDefault(_mdLayout); var _mdList = __webpack_require__(138); var _mdList2 = _interopRequireDefault(_mdList); var _mdMenu = __webpack_require__(149); var _mdMenu2 = _interopRequireDefault(_mdMenu); var _mdRadio = __webpack_require__(163); var _mdRadio2 = _interopRequireDefault(_mdRadio); var _mdSelect = __webpack_require__(169); var _mdSelect2 = _interopRequireDefault(_mdSelect); var _mdSidenav = __webpack_require__(178); var _mdSidenav2 = _interopRequireDefault(_mdSidenav); var _mdSpinner = __webpack_require__(184); var _mdSpinner2 = _interopRequireDefault(_mdSpinner); var _mdSubheader = __webpack_require__(190); var _mdSubheader2 = _interopRequireDefault(_mdSubheader); var _mdSwitch = __webpack_require__(196); var _mdSwitch2 = _interopRequireDefault(_mdSwitch); var _mdTable = __webpack_require__(201); var _mdTable2 = _interopRequireDefault(_mdTable); var _mdTabs = __webpack_require__(228); var _mdTabs2 = _interopRequireDefault(_mdTabs); var _mdToolbar = __webpack_require__(238); var _mdToolbar2 = _interopRequireDefault(_mdToolbar); var _mdTooltip = __webpack_require__(244); var _mdTooltip2 = _interopRequireDefault(_mdTooltip); var _mdWhiteframe = __webpack_require__(249); var _mdWhiteframe2 = _interopRequireDefault(_mdWhiteframe); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var options = { MdCore: _core2.default, MdAvatar: _mdAvatar2.default, MdBackdrop: _mdBackdrop2.default, MdBottomBar: _mdBottomBar2.default, MdButton: _mdButton2.default, MdButtonToggle: _mdButtonToggle2.default, MdCard: _mdCard2.default, MdCheckbox: _mdCheckbox2.default, MdDialog: _mdDialog2.default, MdDivider: _mdDivider2.default, MdIcon: _mdIcon2.default, MdInputContainer: _mdInputContainer2.default, MdLayout: _mdLayout2.default, MdList: _mdList2.default, MdMenu: _mdMenu2.default, MdRadio: _mdRadio2.default, MdSelect: _mdSelect2.default, MdSidenav: _mdSidenav2.default, MdSpinner: _mdSpinner2.default, MdSubheader: _mdSubheader2.default, MdSwitch: _mdSwitch2.default, MdTable: _mdTable2.default, MdTabs: _mdTabs2.default, MdToolbar: _mdToolbar2.default, MdTooltip: _mdTooltip2.default, MdWhiteframe: _mdWhiteframe2.default }; options.install = function (Vue) { for (var component in options) { var componentInstaller = options[component]; if (componentInstaller && component !== 'install') { Vue.use(componentInstaller); } } }; window.VueMaterial = options; exports.default = options; module.exports = exports['default']; /***/ } /******/ ]) }); ; //# sourceMappingURL=vue-material.debug.js.map
app/javascript/mastodon/components/column_back_button.js
MastodonCloud/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; export default class ColumnBackButton extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; handleClick = () => { if (window.history && window.history.length === 1) { this.context.router.history.push('/'); } else { this.context.router.history.goBack(); } } render () { return ( <button onClick={this.handleClick} className='column-back-button'> <i className='fa fa-fw fa-chevron-left column-back-button__icon' /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </button> ); } }
packages/material-ui-icons/src/FiberSmartRecordSharp.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><circle cx="9" cy="12" r="8" /><path d="M17 4.26v2.09c2.33.82 4 3.04 4 5.65s-1.67 4.83-4 5.65v2.09c3.45-.89 6-4.01 6-7.74s-2.55-6.85-6-7.74z" /></React.Fragment> , 'FiberSmartRecordSharp');
node_modules/react/lib/LinkedValueUtils.js
ClaaziX/foodshare
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedValueUtils */ 'use strict'; var _prodInvariant = require('./reactProdInvariant'); var ReactPropTypes = require('./ReactPropTypes'); var ReactPropTypeLocations = require('./ReactPropTypeLocations'); var ReactPropTypesSecret = require('./ReactPropTypesSecret'); var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(inputProps) { !(inputProps.checkedLink == null || inputProps.valueLink == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use checkedLink, you probably don\'t want to use valueLink and vice versa.') : _prodInvariant('87') : void 0; } function _assertValueLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.value == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don\'t want to use valueLink.') : _prodInvariant('88') : void 0; } function _assertCheckedLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.checked == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. If you want to use checked or onChange, you probably don\'t want to use checkedLink') : _prodInvariant('89') : void 0; } var propTypes = { value: function (props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, checked: function (props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, onChange: ReactPropTypes.func }; var loggedTypeFailures = {}; function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { checkPropTypes: function (tagName, props, owner) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop, null, ReactPropTypesSecret); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(owner); process.env.NODE_ENV !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : void 0; } } }, /** * @param {object} inputProps Props for form component * @return {*} current value of the input either from value prop or link. */ getValue: function (inputProps) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.value; } return inputProps.value; }, /** * @param {object} inputProps Props for form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function (inputProps) { if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.value; } return inputProps.checked; }, /** * @param {object} inputProps Props for form component * @param {SyntheticEvent} event change event to handle */ executeOnChange: function (inputProps, event) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.requestChange(event.target.value); } else if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.requestChange(event.target.checked); } else if (inputProps.onChange) { return inputProps.onChange.call(undefined, event); } } }; module.exports = LinkedValueUtils;
node_modules/react-router/es/IndexLink.js
rralian/steckball-react
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import React from 'react'; import Link from './Link'; /** * An <IndexLink> is used to link to an <IndexRoute>. */ var IndexLink = React.createClass({ displayName: 'IndexLink', render: function render() { return React.createElement(Link, _extends({}, this.props, { onlyActiveOnIndex: true })); } }); export default IndexLink;
src/svg-icons/action/assignment-turned-in.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAssignmentTurnedIn = (props) => ( <SvgIcon {...props}> <path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm-2 14l-4-4 1.41-1.41L10 14.17l6.59-6.59L18 9l-8 8z"/> </SvgIcon> ); ActionAssignmentTurnedIn = pure(ActionAssignmentTurnedIn); ActionAssignmentTurnedIn.displayName = 'ActionAssignmentTurnedIn'; export default ActionAssignmentTurnedIn;
node_modules/react/lib/ReactReconciler.js
luisfpinto/react-rpi
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconciler */ 'use strict'; var _prodInvariant = require('./reactProdInvariant'); var ReactRef = require('./ReactRef'); var ReactInstrumentation = require('./ReactInstrumentation'); var invariant = require('fbjs/lib/invariant'); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} the containing host component instance * @param {?object} info about the host container * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (internalInstance, transaction, hostParent, hostContainerInfo, context) { if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement); ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, 'mountComponent'); } } var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context); if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, 'mountComponent'); ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID); } } return markup; }, /** * Returns a value that can be passed to * ReactComponentEnvironment.replaceNodeWithMarkup. */ getHostNode: function (internalInstance) { return internalInstance.getHostNode(); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (internalInstance, safely) { if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, 'unmountComponent'); } } ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(safely); if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, 'unmountComponent'); ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID); } } }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function (internalInstance, nextElement, transaction, context) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && context === internalInstance._context) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for an element created outside a composite to be // deeply mutated and reused. // TODO: Bailing out early is just a perf optimization right? // TODO: Removing the return statement should affect correctness? return; } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement); ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, 'receiveComponent'); } } var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement); if (refsChanged) { ReactRef.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, 'receiveComponent'); ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (internalInstance, transaction, updateBatchNumber) { if (internalInstance._updateBatchNumber !== updateBatchNumber) { // The component's enqueued batch number should always be the current // batch or the following one. !(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'performUpdateIfNecessary: Unexpected batch number (current %s, pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : _prodInvariant('121', updateBatchNumber, internalInstance._updateBatchNumber) : void 0; return; } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, 'performUpdateIfNecessary'); ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement); } } internalInstance.performUpdateIfNecessary(transaction); if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, 'performUpdateIfNecessary'); ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } } }; module.exports = ReactReconciler;
webpack/scenes/RedHatRepositories/components/RepositorySetRepository/RepositorySetRepository.js
snagoor/katello
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { ListView, Spinner, OverlayTrigger, Tooltip, Icon, FieldLevelHelp } from 'patternfly-react'; import { sprintf, translate as __ } from 'foremanReact/common/I18n'; import { yStream } from '../RepositorySetRepositoriesHelpers'; import '../../index.scss'; class RepositorySetRepository extends Component { constructor(props) { super(props); this.state = {}; } setEnabled = () => { this.props.setRepositoryEnabled(this.repoForAction()); }; repoForAction = () => { const { productId, contentId, arch, releasever, label, } = this.props; return { arch, productId, contentId, releasever, label, }; }; reloadEnabledRepos = () => ( this.props.loadEnabledRepos({ ...this.props.enabledPagination, search: this.props.enabledSearch, }, true) ); notifyEnabled = (data) => { const repoName = data.output.repository.name; window.tfm.toastNotifications.notify({ message: sprintf(__("Repository '%(repoName)s' has been enabled."), { repoName }), type: 'success', }); }; reloadAndNotify = async (result) => { if (result && result.success) { await this.reloadEnabledRepos(); await this.setEnabled(); await this.notifyEnabled(result.data); } }; enableRepository = async () => { const result = await this.props.enableRepository(this.repoForAction()); this.reloadAndNotify(result); }; render() { const { displayArch, releasever, type } = this.props; const archLabel = displayArch || __('Unspecified'); const releaseverLabel = releasever || ''; const yStreamHelpText = sprintf( __('This repository is not suggested. Please see additional %(anchorBegin)sdocumentation%(anchorEnd)s prior to use.'), { anchorBegin: '<a href="https://access.redhat.com/articles/1586183">', anchorEnd: '</a>', }, ); // eslint-disable-next-line react/no-danger const yStreamHelp = <span dangerouslySetInnerHTML={{ __html: yStreamHelpText }} />; const shouldDeemphasize = () => type !== 'kickstart' && yStream(releaseverLabel); const repositoryHeading = () => ( <span> {archLabel} {releaseverLabel} {shouldDeemphasize() ? (<FieldLevelHelp content={yStreamHelp} />) : null} </span> ); return ( <ListView.Item heading={repositoryHeading()} className={`list-item-with-divider ${shouldDeemphasize() ? 'deemphasize' : ''}`} leftContent={ this.props.error ? ( <div className="list-error-danger"> <Icon name="times-circle-o" /> </div> ) : null } additionalInfo={ this.state.error ? [ <ListView.InfoItem key="error" stacked className="list-error-danger"> {this.state.error.displayMessage} </ListView.InfoItem>, ] : null } actions={ <Spinner loading={this.props.loading} inline> <OverlayTrigger overlay={<Tooltip id="enable">{__('Enable')}</Tooltip>} placement="bottom" trigger={['hover', 'focus']} rootClose={false} > <button onClick={this.enableRepository} style={{ backgroundColor: 'initial', border: 'none', color: '#0388ce', }} > <i className={cx('fa-2x', 'fa fa-plus-circle')} /> </button> </OverlayTrigger> </Spinner> } stacked /> ); } } RepositorySetRepository.propTypes = { contentId: PropTypes.number.isRequired, productId: PropTypes.number.isRequired, displayArch: PropTypes.string, arch: PropTypes.string, releasever: PropTypes.string, type: PropTypes.string, label: PropTypes.string, enabledSearch: PropTypes.shape({ query: PropTypes.string, searchList: PropTypes.string, // Disabling rule as existing code failed due to an eslint-plugin-react update // eslint-disable-next-line react/forbid-prop-types filters: PropTypes.array, }), enabledPagination: PropTypes.shape({ page: PropTypes.number, perPage: PropTypes.number, }).isRequired, loading: PropTypes.bool, error: PropTypes.bool, setRepositoryEnabled: PropTypes.func.isRequired, loadEnabledRepos: PropTypes.func.isRequired, enableRepository: PropTypes.func.isRequired, }; RepositorySetRepository.defaultProps = { type: '', label: '', releasever: undefined, arch: undefined, displayArch: undefined, enabledSearch: {}, loading: false, error: false, }; export default RepositorySetRepository;
ajax/libs/rxjs/2.3.19/rx.compat.js
NameFILIP/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 }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var deprecate = Rx.helpers.deprecate = function (name, alternative) { /*if (typeof console !== "undefined" && typeof console.warn === "function") { console.warn(name + ' is deprecated, use ' + alternative + ' instead.', new Error('').stack); }*/ } /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 supportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch (e) { supportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } var isArguments = function(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b : // but treat `-0` vs. `+0` as not equal (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // 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; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function 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)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dueTime); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; var onGlobalPostMessage = function (event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); var CatchScheduler = (function (__super__) { 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__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); } CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; 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; } }; }; 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; }; CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { var notification = new Notification('E'); notification.exception = e; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch (err) { observer.onError(err); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch (err) { observer.onError(err); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * 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. * @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, 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()); }); }; /** * 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.prototype.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. */ 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 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 (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); 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; })(); /** * 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 observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { subject.onNext(value); subject.onCompleted(); }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var 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 StringIterable(str) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(str) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { if (this._i < this._l) { var val = this._s.charAt(this._i++); return { done: false, value: val }; } else { return doneEnumerator; } }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { if (this._i < this._l) { var val = this._a[this._i++]; return { done: false, value: val }; } else { return doneEnumerator; } }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); var list = Object(iterable), it = getIterable(list); return new AnonymousObservable(function (observer) { var i = 0; return scheduler.scheduleRecursive(function (self) { var next; try { next = it.next(); } catch (e) { observer.onError(e); return; } if (next.done) { observer.onCompleted(); return; } var result = next.value; if (mapFn && isFunction(mapFn)) { try { result = mapFn.call(thisArg, result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { deprecate('fromArray', 'from'); isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { return observableOf(null, arguments); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { return observableOf(scheduler, slice.call(arguments, 1)); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** @deprecated use return or just */ Observable.returnValue = function () { deprecate('returnValue', 'return or just'); return observableReturn.apply(null, arguments); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = 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.catchError = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * @deprecated use #catch or #catchError instead. */ observableProto.catchException = function (handlerOrSecond) { deprecate('catchException', 'catch or catchError'); return this.catchError(handlerOrSecond); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = function () { return enumerableOf(argsOrArray(arguments, 0)).catchError(); }; /** * @deprecated use #catch or #catchError instead. */ Observable.catchException = function () { deprecate('catchException', 'catch or catchError'); return observableCatch.apply(null, arguments); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { return enumerableOf(argsOrArray(arguments, 0)).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatAll = function () { return this.merge(1); }; /** @deprecated Use `concatAll` instead. */ observableProto.concatObservable = function () { deprecate('concatObservable', 'concatAll'); return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = []; function subscribe(xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support isPromise(xs) && (xs = observableFromPromise(xs)); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(subscription); if (q.length > 0) { subscribe(q.shift()); } else { activeCount--; isStopped && activeCount === 0 && observer.onCompleted(); } })); } group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; activeCount === 0 && observer.onCompleted(); })); return group; }); }; /** * 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 observableOf(scheduler, sources).mergeAll(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(innerSubscription); isStopped && group.length === 1 && observer.onCompleted(); })); }, observer.onError.bind(observer), function () { isStopped = true; group.length === 1 && observer.onCompleted(); })); return group; }); }; /** * @deprecated use #mergeAll instead. */ observableProto.mergeObservable = function () { deprecate('mergeObservable', 'mergeAll'); return this.mergeAll.apply(this, arguments); }; /** * 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), self, 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 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)); }; /** * 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. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (onError) { try { onError(err); } catch (e) { observer.onError(e); } } observer.onError(err); }, function () { if (onCompleted) { try { onCompleted(); } catch (e) { observer.onError(e); } } observer.onCompleted(); }); }); }; /** @deprecated use #do or #tap instead. */ observableProto.doAction = function () { deprecate('doAction', 'do or tap'); return this.tap.apply(this, arguments); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(arguments.length === 2 ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, arguments.length === 2 ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, arguments.length === 2 ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * 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. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { !hasValue && hasSeed && observer.onNext(seed); observer.onCompleted(); } ); }); }; /** * 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(); }); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new Error(argumentOutOfRange); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { observer.onError(e); return; } } hashSet.push(key) && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var selectorFn = isFunction(selector) ? selector : function () { return selector; }, source = this; return new AnonymousObservable(function (observer) { var count = 0; return source.subscribe(function (value) { var result; try { result = selectorFn.call(thisArg, value, count++, source); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} prop The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (prop) { return this.map(function (x) { return x[prop]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var 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)); }); }; /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }); }; 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)); var AutoDetachObserver = (function (__super__) { inherits(AutoDetachObserver, __super__); function AutoDetachObserver(observer) { __super__.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { !noError && this.dispose(); } }; AutoDetachObserverPrototype.error = function (err) { try { this.observer.onError(err); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); 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));
src/views/LoginView.js
ghartong/react_falcor
import React from 'react' import Falcor from 'falcor' import falcorModel from '../falcorModel' import {connect} from 'react-redux' import {bindActionCreators} from 'redux' import {LoginForm} from '../components/LoginForm' import {Snackbar} from 'material-ui' const mapStateToProps = (state) => ({ ...state }) //Add reducers here const mapDispatchToProps = (dispatch) => ({ }) class LoginView extends React.Component { constructor(props) { super(props) this.login = this.login.bind(this) this.state = { error: null } } async login(credentials) { console.log('credentials', credentials) await falcorModel .call(['login'],[credentials]) .then( (result) => result ) const tokenRes = await falcorModel.getValue('login.token') console.log('tokenRes', tokenRes) if (tokenRes === 'INVALID') { const errorRes = await falcorModel.getValue('login.error') this.setState({error: errorRes}) return } if (tokenRes) { const username = await falcorModel.getValue('login.username') const role = await falcorModel.getValue('login.role') localStorage.setItem('token', tokenRes) localStorage.setItem('username', username) localStorage.setItem('role', role) this.props.history.pushState(null, '/dashboard') } return } render() { return ( <div> <div style={{maxWidth: 450, margin: '0 auto'}}> <LoginForm onSubmit={this.login} /> </div> <Snackbar autoHideDuration={4000} open={!!this.state.error} message={this.state.error || ''} onRequestClose={ () => null} /> </div> ) } } export default connect( mapStateToProps, mapDispatchToProps )(LoginView)
ext-4.2.2.1144/docs/output/Ext.ux.GroupTabPanel.js
ashwinpote/Ext_JS_POC
Ext.data.JsonP.Ext_ux_GroupTabPanel({"alternateClassNames":[],"aliases":{"widget":["grouptabpanel"]},"enum":null,"parentMixins":["Ext.Queryable","Ext.state.Stateful","Ext.util.Animate","Ext.util.ElementContainer","Ext.util.Floating","Ext.util.Observable","Ext.util.Positionable","Ext.util.Renderable"],"tagname":"class","subclasses":[],"extends":"Ext.Container","uses":[],"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 '><a href='#!/api/Ext.Component' rel='Ext.Component' class='docClass'>Ext.Component</a><div class='subclass '><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='docClass'>Ext.container.AbstractContainer</a><div class='subclass '><a href='#!/api/Ext.container.Container' rel='Ext.container.Container' class='docClass'>Ext.container.Container</a><div class='subclass '><strong>Ext.ux.GroupTabPanel</strong></div></div></div></div></div></div><h4>Inherited mixins</h4><div class='dependency'><a href='#!/api/Ext.Queryable' rel='Ext.Queryable' class='docClass'>Ext.Queryable</a></div><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.Floating' rel='Ext.util.Floating' class='docClass'>Ext.util.Floating</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>Requires</h4><div class='dependency'><a href='#!/api/Ext.tree.Panel' rel='Ext.tree.Panel' class='docClass'>Ext.tree.Panel</a></div><div class='dependency'><a href='#!/api/Ext.ux.GroupTabRenderer' rel='Ext.ux.GroupTabRenderer' class='docClass'>Ext.ux.GroupTabRenderer</a></div><h4>Files</h4><div class='dependency'><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel' target='_blank'>GroupTabPanel.js</a></div></pre><div class='doc-contents'><p>A TabPanel with grouping support.</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-activeItem' class='member first-child inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-cfg-activeItem' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-cfg-activeItem' class='name expandable'>activeItem</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span></div><div class='description'><div class='short'>A string component id or the numeric index of the component that should be\ninitially activated within the container's...</div><div class='long'><p>A string component id or the numeric index of the component that should be\ninitially activated within the container's layout on render. For example,\nactiveItem: 'item-1' or activeItem: 0 (index 0 = the first item in the\ncontainer's collection). activeItem only applies to layout styles that can\ndisplay items one at a time (like <a href=\"#!/api/Ext.layout.container.Card\" rel=\"Ext.layout.container.Card\" class=\"docClass\">Ext.layout.container.Card</a> and\n<a href=\"#!/api/Ext.layout.container.Fit\" rel=\"Ext.layout.container.Fit\" class=\"docClass\">Ext.layout.container.Fit</a>).</p>\n <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='cfg-anchorSize' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.Container' rel='Ext.container.Container' class='defined-in docClass'>Ext.container.Container</a><br/><a href='source/Anchor.html#Ext-container-Container-cfg-anchorSize' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.Container-cfg-anchorSize' class='name expandable'>anchorSize</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span></div><div class='description'><div class='short'>Defines the anchoring size of container. ...</div><div class='long'><p>Defines the anchoring size of container.\nEither a number to define the width of the container or an object with <code>width</code> and <code>height</code> fields.</p>\n</div></div></div><div id='cfg-autoDestroy' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-cfg-autoDestroy' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-cfg-autoDestroy' class='name expandable'>autoDestroy</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>If true the container will automatically destroy any contained component that is removed\nfrom it, else destruction mu...</div><div class='long'><p>If true the container will automatically destroy any contained component that is removed\nfrom it, else destruction must be handled manually.</p>\n<p>Defaults to: <code>true</code></p> <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='cfg-autoEl' 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-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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.ux.GroupTabPanel'>Ext.ux.GroupTabPanel</span><br/><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel-cfg-baseCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.ux.GroupTabPanel-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>Ext.baseCSSPrefix + 'grouptabpanel'</code></p><p>Overrides: <a href='#!/api/Ext.container.AbstractContainer-cfg-baseCls' rel='Ext.container.AbstractContainer-cfg-baseCls' class='docClass'>Ext.container.AbstractContainer.baseCls</a></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-bubbleEvents' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-cfg-bubbleEvents' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-cfg-bubbleEvents' class='name expandable'>bubbleEvents</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 be bubbled to any parent container. ...</div><div class='long'><p>An array of events that, when fired, should be bubbled to any parent container.\nSee <a href=\"#!/api/Ext.util.Observable-method-enableBubble\" rel=\"Ext.util.Observable-method-enableBubble\" class=\"docClass\">Ext.util.Observable.enableBubble</a>.</p>\n <p>Available since: <b>3.4.0</b></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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-defaultType' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-cfg-defaultType' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-cfg-defaultType' class='name expandable'>defaultType</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>The default xtype of child Components to create in this Container when\na child item is specified as a raw configurati...</div><div class='long'><p>The default <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">xtype</a> of child Components to create in this Container when\na child item is specified as a raw configuration object, rather than as an instantiated Component.</p>\n<p>Defaults to: <code>&quot;panel&quot;</code></p> <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='cfg-defaults' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-cfg-defaults' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-cfg-defaults' class='name expandable'>defaults</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>/<a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a></span></div><div class='description'><div class='short'>This option is a means of applying default settings to all added items whether added\nthrough the items config or via ...</div><div class='long'><p>This option is a means of applying default settings to all added items whether added\nthrough the <a href=\"#!/api/Ext.container.AbstractContainer-cfg-items\" rel=\"Ext.container.AbstractContainer-cfg-items\" class=\"docClass\">items</a> config or via the <a href=\"#!/api/Ext.container.AbstractContainer-method-add\" rel=\"Ext.container.AbstractContainer-method-add\" class=\"docClass\">add</a> or <a href=\"#!/api/Ext.container.AbstractContainer-method-insert\" rel=\"Ext.container.AbstractContainer-method-insert\" class=\"docClass\">insert</a> methods.</p>\n\n<p>Defaults are applied to both config objects and instantiated components conditionally\nso as not to override existing properties in the item (see <a href=\"#!/api/Ext-method-applyIf\" rel=\"Ext-method-applyIf\" class=\"docClass\">Ext.applyIf</a>).</p>\n\n<p>If the defaults option is specified as a function, then the function will be called\nusing this Container as the scope (<code>this</code> reference) and passing the added item as\nthe first parameter. Any resulting object from that call is then applied to the item\nas default properties.</p>\n\n<p>For example, to automatically apply padding to the body of each of a set of\ncontained <a href=\"#!/api/Ext.panel.Panel\" rel=\"Ext.panel.Panel\" class=\"docClass\">Ext.panel.Panel</a> items, you could pass:\n<code>defaults: {bodyStyle:'padding:15px'}</code>.</p>\n\n<p>Usage:</p>\n\n<pre><code>defaults: { // defaults are applied to items, not the container\n autoScroll: true\n},\nitems: [\n // default will not be applied here, panel1 will be autoScroll: false\n {\n xtype: 'panel',\n id: 'panel1',\n autoScroll: false\n },\n // this component will have autoScroll: true\n new <a href=\"#!/api/Ext.panel.Panel\" rel=\"Ext.panel.Panel\" class=\"docClass\">Ext.panel.Panel</a>({\n id: 'panel2'\n })\n]\n</code></pre>\n <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='cfg-detachOnRemove' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-cfg-detachOnRemove' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-cfg-detachOnRemove' class='name expandable'>detachOnRemove</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>True to move any component to the detachedBody when the component is\nremoved from this container. ...</div><div class='long'><p>True to move any component to the <a href=\"#!/api/Ext-method-getDetachedBody\" rel=\"Ext-method-getDetachedBody\" class=\"docClass\">detachedBody</a> when the component is\nremoved from this container. This option is only applicable when the component is not destroyed while\nbeing removed, see <a href=\"#!/api/Ext.container.AbstractContainer-cfg-autoDestroy\" rel=\"Ext.container.AbstractContainer-cfg-autoDestroy\" class=\"docClass\">autoDestroy</a> and <a href=\"#!/api/Ext.container.AbstractContainer-method-remove\" rel=\"Ext.container.AbstractContainer-method-remove\" class=\"docClass\">remove</a>. If this option is set to false, the DOM\nof the component will remain in the current place until it is explicitly moved.</p>\n<p>Defaults to: <code>true</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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-items' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-cfg-items' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-cfg-items' class='name expandable'>items</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>[]</span></div><div class='description'><div class='short'>A single item, or an array of child Components to be added to this container\n\nUnless configured with a layout, a Cont...</div><div class='long'><p>A single item, or an array of child Components to be added to this container</p>\n\n<p><strong>Unless configured with a <a href=\"#!/api/Ext.container.AbstractContainer-cfg-layout\" rel=\"Ext.container.AbstractContainer-cfg-layout\" class=\"docClass\">layout</a>, a Container simply renders child\nComponents serially into its encapsulating element and performs no sizing or\npositioning upon them.</strong></p>\n\n<p>Example:</p>\n\n<pre><code>// specifying a single item\nitems: {...},\nlayout: 'fit', // The single items is sized to fit\n\n// specifying multiple items\nitems: [{...}, {...}],\nlayout: 'hbox', // The items are arranged horizontally\n</code></pre>\n\n<p>Each item may be:</p>\n\n<ul>\n<li>A <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Component</a></li>\n<li>A Component configuration object</li>\n</ul>\n\n\n<p>If a configuration object is specified, the actual type of Component to be\ninstantiated my be indicated by using the <a href=\"#!/api/Ext.Component-cfg-xtype\" rel=\"Ext.Component-cfg-xtype\" class=\"docClass\">xtype</a> option.</p>\n\n<p>Every Component class has its own <a href=\"#!/api/Ext.Component-cfg-xtype\" rel=\"Ext.Component-cfg-xtype\" class=\"docClass\">xtype</a>.</p>\n\n<p>If an <a href=\"#!/api/Ext.Component-cfg-xtype\" rel=\"Ext.Component-cfg-xtype\" class=\"docClass\">xtype</a> is not explicitly specified, the\n<a href=\"#!/api/Ext.container.AbstractContainer-cfg-defaultType\" rel=\"Ext.container.AbstractContainer-cfg-defaultType\" class=\"docClass\">defaultType</a> for the Container is used, which by default is usually <code>panel</code>.</p>\n\n<h1>Notes:</h1>\n\n<p>Ext uses lazy rendering. Child Components will only be rendered\nshould it become necessary. Items are automatically laid out when they are first\nshown (no sizing is done while hidden), or in response to a <a href=\"#!/api/Ext.container.AbstractContainer-method-doLayout\" rel=\"Ext.container.AbstractContainer-method-doLayout\" class=\"docClass\">doLayout</a> call.</p>\n\n<p>Do not specify <a href=\"#!/api/Ext.panel.Panel-cfg-contentEl\" rel=\"Ext.panel.Panel-cfg-contentEl\" class=\"docClass\">contentEl</a> or\n<a href=\"#!/api/Ext.panel.Panel-cfg-html\" rel=\"Ext.panel.Panel-cfg-html\" class=\"docClass\">html</a> with <code>items</code>.</p>\n <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='cfg-layout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-cfg-layout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-cfg-layout' class='name expandable'>layout</a><span> : <a href=\"#!/api/Ext.enums.Layout\" rel=\"Ext.enums.Layout\" class=\"docClass\">Ext.enums.Layout</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span></div><div class='description'><div class='short'>Important: In order for child items to be correctly sized and\npositioned, typically a layout manager must be specifie...</div><div class='long'><p><strong>Important</strong>: In order for child items to be correctly sized and\npositioned, typically a layout manager <strong>must</strong> be specified through\nthe <code>layout</code> configuration option.</p>\n\n<p>The sizing and positioning of child <a href=\"#!/api/Ext.container.AbstractContainer-cfg-items\" rel=\"Ext.container.AbstractContainer-cfg-items\" class=\"docClass\">items</a> is the responsibility of\nthe Container's layout manager which creates and manages the type of layout\nyou have in mind. For example:</p>\n\n<p>If the layout configuration is not explicitly specified for\na general purpose container (e.g. Container or Panel) the\n<a href=\"#!/api/Ext.layout.container.Auto\" rel=\"Ext.layout.container.Auto\" class=\"docClass\">default layout manager</a> will be used\nwhich does nothing but render child components sequentially into the\nContainer (no sizing or positioning will be performed in this situation).</p>\n\n<p><strong>layout</strong> may be specified as either as an Object or as a String:</p>\n\n<h2>Specify as an Object</h2>\n\n<p>Example usage:</p>\n\n<pre><code>layout: {\n type: 'vbox',\n align: 'left'\n}\n</code></pre>\n\n<ul>\n<li><p><strong>type</strong></p>\n\n<p>The layout type to be used for this container. If not specified,\na default <a href=\"#!/api/Ext.layout.container.Auto\" rel=\"Ext.layout.container.Auto\" class=\"docClass\">Ext.layout.container.Auto</a> will be created and used.</p>\n\n<p>Valid layout <code>type</code> values are listed in <a href=\"#!/api/Ext.enums.Layout\" rel=\"Ext.enums.Layout\" class=\"docClass\">Ext.enums.Layout</a>.</p></li>\n<li><p>Layout specific configuration properties</p>\n\n<p>Additional layout specific configuration properties may also be\nspecified. For complete details regarding the valid config options for\neach layout type, see the layout class corresponding to the <code>type</code>\nspecified.</p></li>\n</ul>\n\n\n<h2>Specify as a String</h2>\n\n<p>Example usage:</p>\n\n<pre><code>layout: 'vbox'\n</code></pre>\n\n<ul>\n<li><p><strong>layout</strong></p>\n\n<p>The layout <code>type</code> to be used for this container (see <a href=\"#!/api/Ext.enums.Layout\" rel=\"Ext.enums.Layout\" class=\"docClass\">Ext.enums.Layout</a>\nfor list of valid values).</p>\n\n<p>Additional layout specific configuration properties. For complete\ndetails regarding the valid config options for each layout type, see the\nlayout class corresponding to the <code>layout</code> specified.</p></li>\n</ul>\n\n\n<h2>Configuring the default layout type</h2>\n\n<p>If a certain Container class has a default layout (For example a <a href=\"#!/api/Ext.toolbar.Toolbar\" rel=\"Ext.toolbar.Toolbar\" class=\"docClass\">Toolbar</a>\nwith a default <code>Box</code> layout), then to simply configure the default layout,\nuse an object, but without the <code>type</code> property:</p>\n\n<pre><code>xtype: 'toolbar',\nlayout: {\n pack: 'center'\n}\n</code></pre>\n <p>Available since: <b>2.3.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-cfg-renderTpl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-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'>End Definitions\n\nAn XTemplate used to create the internal structure inside this Component's encapsulating\nElement. ...</div><div class='long'><p>End Definitions</p>\n\n<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.container.AbstractContainer-method-getEl\" rel=\"Ext.container.AbstractContainer-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.container.AbstractContainer-method-getEl\" rel=\"Ext.container.AbstractContainer-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.container.AbstractContainer-cfg-renderSelectors\" rel=\"Ext.container.AbstractContainer-cfg-renderSelectors\" class=\"docClass\">renderSelectors</a> and <a href=\"#!/api/Ext.container.AbstractContainer-cfg-childEls\" rel=\"Ext.container.AbstractContainer-cfg-childEls\" class=\"docClass\">childEls</a> options.</p>\n<p>Defaults to: <code>'{%this.renderContainer(out,values)%}'</code></p><p>Overrides: <a href='#!/api/Ext.AbstractComponent-cfg-renderTpl' rel='Ext.AbstractComponent-cfg-renderTpl' class='docClass'>Ext.AbstractComponent.renderTpl</a></p></div></div></div><div id='cfg-resizable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-suspendLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-cfg-suspendLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-cfg-suspendLayout' class='name expandable'>suspendLayout</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>If true, suspend calls to doLayout. ...</div><div class='long'><p>If true, suspend calls to doLayout. Useful when batching multiple adds to a container\nand not passing them as multiple arguments or an array.</p>\n<p>Defaults to: <code>false</code></p></div></div></div><div id='cfg-toFrontOnShow' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-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-cfg-weight' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-weight' class='name expandable'>weight</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span></div><div class='description'><div class='short'>A value to control how Components are laid out in a Border layout or as docked items. ...</div><div class='long'><p>A value to control how Components are laid out in a <a href=\"#!/api/Ext.layout.container.Border\" rel=\"Ext.layout.container.Border\" class=\"docClass\">Border</a> layout or as docked items.</p>\n\n<p>In a Border layout, this can control how the regions (not the center) region lay out if the west or east take full height\nor if the north or south region take full width. Also look at the <a href=\"#!/api/Ext.layout.container.Border-cfg-regionWeights\" rel=\"Ext.layout.container.Border-cfg-regionWeights\" class=\"docClass\">Ext.layout.container.Border.regionWeights</a> on the Border layout. An example to show how you can\ntake control of this is:</p>\n\n<pre><code><a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.container.Viewport\" rel=\"Ext.container.Viewport\" class=\"docClass\">Ext.container.Viewport</a>', {\n layout : 'border',\n defaultType : 'panel',\n items : [\n {\n region : 'north',\n title : 'North',\n height : 100\n },\n {\n region : 'south',\n title : 'South',\n height : 100,\n weight : -25\n },\n {\n region : 'west',\n title : 'West',\n width : 200,\n weight : 15\n },\n {\n region : 'east',\n title : 'East',\n width : 200\n },\n {\n region : 'center',\n title : 'center'\n }\n ]\n});\n</code></pre>\n\n<p>If docked items, the weight will order how the items are laid out. Here is an example to put a <a href=\"#!/api/Ext.toolbar.Toolbar\" rel=\"Ext.toolbar.Toolbar\" class=\"docClass\">Ext.toolbar.Toolbar</a> above\na <a href=\"#!/api/Ext.panel.Panel\" rel=\"Ext.panel.Panel\" class=\"docClass\">Ext.panel.Panel</a>'s header:</p>\n\n<pre><code><a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.panel.Panel\" rel=\"Ext.panel.Panel\" class=\"docClass\">Ext.panel.Panel</a>', {\n renderTo : document.body,\n width : 300,\n height : 300,\n title : 'Panel',\n html : 'Panel Body',\n dockedItems : [\n {\n xtype : 'toolbar',\n items : [\n {\n text : 'Save'\n }\n ]\n },\n {\n xtype : 'toolbar',\n weight : -10,\n items : [\n {\n text : 'Remove'\n }\n ]\n }\n ]\n});\n</code></pre>\n<p>Defaults to: <code>0</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-ariaRole' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-property-ariaRole' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-property-ariaRole' class='name expandable'>ariaRole</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>'presentation'</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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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', 'Table']</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-isContainer' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-property-isContainer' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-property-isContainer' class='name expandable'>isContainer</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 in this class to identify an object as an instantiated Container, or subclass thereof. ...</div><div class='long'><p><code>true</code> in this class to identify an object as an instantiated Container, 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-isQueryable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Queryable' rel='Ext.Queryable' class='defined-in docClass'>Ext.Queryable</a><br/><a href='source/Queryable.html#Ext-Queryable-property-isQueryable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Queryable-property-isQueryable' class='name expandable'>isQueryable</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-items' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-property-items' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-property-items' class='name not-expandable'>items</a><span> : <a href=\"#!/api/Ext.util.AbstractMixedCollection\" rel=\"Ext.util.AbstractMixedCollection\" class=\"docClass\">Ext.util.AbstractMixedCollection</a></span></div><div class='description'><div class='short'><p>The MixedCollection containing all the child items of this container.</p>\n</div><div class='long'><p>The MixedCollection containing all the child items of this container.</p>\n <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='property-layoutCounter' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-property-layoutCounter' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-property-layoutCounter' class='name expandable'>layoutCounter</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 container layout calls made on this object. ...</div><div class='long'><p>The number of container layout calls made on this object.</p>\n<p>Defaults to: <code>0</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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-rootCls' 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-rootCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-rootCls' class='name expandable'>rootCls</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 + 'body'</code></p></div></div></div><div id='property-scrollFlags' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><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-zIndexManager' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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></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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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.ux.GroupTabPanel</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<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</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-add' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-add' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-add' class='name expandable'>add</a>( <span class='pre'>component</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>[]/<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Adds Component(s) to this Container. ...</div><div class='long'><p>Adds <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Component</a>(s) to this Container.</p>\n\n<h2>Description:</h2>\n\n<ul>\n<li>Fires the <a href=\"#!/api/Ext.container.AbstractContainer-event-beforeadd\" rel=\"Ext.container.AbstractContainer-event-beforeadd\" class=\"docClass\">beforeadd</a> event before adding.</li>\n<li>The Container's <a href=\"#!/api/Ext.container.AbstractContainer-cfg-defaults\" rel=\"Ext.container.AbstractContainer-cfg-defaults\" class=\"docClass\">default config values</a> will be applied\naccordingly (see <code><a href=\"#!/api/Ext.container.AbstractContainer-cfg-defaults\" rel=\"Ext.container.AbstractContainer-cfg-defaults\" class=\"docClass\">defaults</a></code> for details).</li>\n<li>Fires the <code><a href=\"#!/api/Ext.container.AbstractContainer-event-add\" rel=\"Ext.container.AbstractContainer-event-add\" class=\"docClass\">add</a></code> event after the component has been added.</li>\n</ul>\n\n\n<h2>Notes:</h2>\n\n<p>If the Container is <strong>already rendered</strong> when <code>add</code>\nis called, it will render the newly added Component into its content area.</p>\n\n<p><strong>If</strong> the Container was configured with a size-managing <a href=\"#!/api/Ext.container.AbstractContainer-cfg-layout\" rel=\"Ext.container.AbstractContainer-cfg-layout\" class=\"docClass\">layout</a> manager,\nthe Container will recalculate its internal layout at this time too.</p>\n\n<p>Note that the default layout manager simply renders child Components sequentially\ninto the content area and thereafter performs no sizing.</p>\n\n<p>If adding multiple new child Components, pass them as an array to the <code>add</code> method,\nso that only one layout recalculation is performed.</p>\n\n<pre><code>tb = new <a href=\"#!/api/Ext.toolbar.Toolbar\" rel=\"Ext.toolbar.Toolbar\" class=\"docClass\">Ext.toolbar.Toolbar</a>({\n renderTo: document.body\n}); // toolbar is rendered\n// add multiple items.\n// (<a href=\"#!/api/Ext.container.AbstractContainer-cfg-defaultType\" rel=\"Ext.container.AbstractContainer-cfg-defaultType\" class=\"docClass\">defaultType</a> for <a href=\"#!/api/Ext.toolbar.Toolbar\" rel=\"Ext.toolbar.Toolbar\" class=\"docClass\">Toolbar</a> is 'button')\ntb.add([{text:'Button 1'}, {text:'Button 2'}]);\n</code></pre>\n\n<p>To inject components between existing ones, use the <a href=\"#!/api/Ext.container.AbstractContainer-method-insert\" rel=\"Ext.container.AbstractContainer-method-insert\" class=\"docClass\">insert</a> method.</p>\n\n<h2>Warning:</h2>\n\n<p>Components directly managed by the BorderLayout layout manager may not be removed\nor added. See the Notes for <a href=\"#!/api/Ext.layout.container.Border\" rel=\"Ext.layout.container.Border\" class=\"docClass\">BorderLayout</a> for\nmore details.</p>\n <p>Available since: <b>2.3.0</b></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/Object\" rel=\"Object\" class=\"docClass\">Object</a>[]/<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>.../<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>...<div class='sub-desc'><p>Either one or more Components to add or an Array of Components to add.\nSee <code><a href=\"#!/api/Ext.container.AbstractContainer-cfg-items\" rel=\"Ext.container.AbstractContainer-cfg-items\" class=\"docClass\">items</a></code> for additional information.</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>[]/<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>The Components that were added.</p>\n</div></li></ul></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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-afterComponentLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-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</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</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</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</div></li></ul><p>Overrides: <a href='#!/api/Ext.Component-method-afterComponentLayout' rel='Ext.Component-method-afterComponentLayout' class='docClass'>Ext.Component.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-afterLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-afterLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-afterLayout' class='name expandable'>afterLayout</a>( <span class='pre'>layout</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Invoked after the Container has laid out (and rendered if necessary)\nits child Components. ...</div><div class='long'><p>Invoked after the Container has laid out (and rendered if necessary)\nits child Components.</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'>layout</span> : <a href=\"#!/api/Ext.layout.container.Container\" rel=\"Ext.layout.container.Container\" class=\"docClass\">Ext.layout.container.Container</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-afterRender' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-event-show\" rel=\"Ext.Component-event-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-applyDefaults' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-applyDefaults' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-applyDefaults' class='name expandable'>applyDefaults</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-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-applyTargetCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-applyTargetCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-applyTargetCls' class='name expandable'>applyTargetCls</a>( <span class='pre'>targetCls</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>The targetCls is a CSS class that the layout needs added to the targetEl. ...</div><div class='long'><p>The targetCls is a CSS class that the layout needs added to the targetEl. The targetEl is where the container's\nchildren are rendered and is usually just the main el. Some containers (e.g. panels) use a body instead.</p>\n\n<p>In general, if a class overrides getTargetEl it will also need to override this method. This is necessary to\navoid a post-render step to add the targetCls.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>targetCls</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-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.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-beforeDestroy' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-beforeDestroy' class='name expandable'>beforeDestroy</a>( <span class='pre'></span> )<strong class='private signature' >private</strong><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 <p>Available since: <b>2.3.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-beforeDestroy' rel='Ext.AbstractComponent-method-beforeDestroy' class='docClass'>Ext.AbstractComponent.beforeDestroy</a></p></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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-beforeRender' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-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.Component-method-beforeRender' rel='Ext.Component-method-beforeRender' class='docClass'>Ext.Component.beforeRender</a></p></div></div></div><div id='method-beforeSetPosition' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-bubble' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-cascade' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-cascade' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-cascade' class='name expandable'>cascade</a>( <span class='pre'>fn, [scope], [args]</span> ) : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.Container</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Cascades down the component/container heirarchy from this component (passed in\nthe first call), calling the specified...</div><div class='long'><p>Cascades down the component/container heirarchy from this component (passed in\nthe first call), calling the specified function with each component. The scope\n(this reference) of the function call will be the scope provided or the current\ncomponent. The arguments to the function will be the args provided or the current\ncomponent. If the function returns false at any point, the cascade is stopped on\nthat branch.</p>\n <p>Available since: <b>2.3.0</b></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 component)</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. The current component\nalways passed as the last argument.</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</a></span><div class='sub-desc'><p>this</p>\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-child' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Queryable' rel='Ext.Queryable' class='defined-in docClass'>Ext.Queryable</a><br/><a href='source/Queryable.html#Ext-Queryable-method-child' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Queryable-method-child' class='name expandable'>child</a>( <span class='pre'>[selector]</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>Retrieves the first direct child of this container which matches the passed selector or component. ...</div><div class='long'><p>Retrieves the first direct child of this container which matches the passed selector or component.\nThe passed in selector must comply with an <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">Ext.ComponentQuery</a> selector, or it can be an actual <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</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>/<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> (optional)<div class='sub-desc'><p>An <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">Ext.ComponentQuery</a> selector. If no selector is\nspecified, the first child will be returned.</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 href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> The matching child <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> (or <code>null</code> if no match was found).</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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-contains' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-contains' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-contains' class='name expandable'>contains</a>( <span class='pre'>comp, [deep]</span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Determines whether the passed Component is either an immediate child of this Container,\nor whether it is a descendant. ...</div><div class='long'><p>Determines whether the passed Component is either an immediate child of this Container,\nor whether it is a descendant.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>comp</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The Component to test.</p>\n</div></li><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 test for the Component being a descendant at any level.</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 the passed Component is contained at the specified level.</p>\n</div></li></ul></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-createTreeStore' 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.ux.GroupTabPanel'>Ext.ux.GroupTabPanel</span><br/><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel-method-createTreeStore' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.ux.GroupTabPanel-method-createTreeStore' class='name expandable'>createTreeStore</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Creates the TreeStore used by the GroupTabBar. ...</div><div class='long'><p>Creates the TreeStore used by the GroupTabBar.</p>\n</div></div></div><div id='method-deleteMembers' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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.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-detachComponent' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-detachComponent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-detachComponent' class='name expandable'>detachComponent</a>( <span class='pre'>component</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Detach a component from the DOM ...</div><div class='long'><p>Detach a component from the DOM</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>component</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-disable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-disable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-disable' class='name expandable'>disable</a>( <span class='pre'>[silent]</span> ) : <a href=\"#!/api/Ext.container.AbstractContainer\" rel=\"Ext.container.AbstractContainer\" class=\"docClass\">Ext.container.AbstractContainer</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Inherit docs\nDisable all immediate children that was previously disabled\nOverride disable because onDisable only gets...</div><div class='long'><p>Inherit docs\nDisable all immediate children that was previously disabled\nOverride disable because onDisable only gets called when rendered</p>\n\n<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><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.container.AbstractContainer\" rel=\"Ext.container.AbstractContainer\" class=\"docClass\">Ext.container.AbstractContainer</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-disable' rel='Ext.AbstractComponent-method-disable' class='docClass'>Ext.AbstractComponent.disable</a></p></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-doLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-doLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-doLayout' class='name expandable'>doLayout</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'>Manually force this container's layout to be recalculated. ...</div><div class='long'><p>Manually force this container's layout to be recalculated. The framework uses this internally to refresh layouts\nform most cases.</p>\n <p>Available since: <b>2.3.0</b></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-doRemove' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-doRemove' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-doRemove' class='name expandable'>doRemove</a>( <span class='pre'>component, doDestroy</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'>component</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>doDestroy</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-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-down' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Queryable' rel='Ext.Queryable' class='defined-in docClass'>Ext.Queryable</a><br/><a href='source/Queryable.html#Ext-Queryable-method-down' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Queryable-method-down' class='name expandable'>down</a>( <span class='pre'>[selector]</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>Retrieves the first descendant of this container which matches the passed selector. ...</div><div class='long'><p>Retrieves the first descendant of this container which matches the passed selector.\nThe passed in selector must comply with an <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">Ext.ComponentQuery</a> selector, or it can be an actual <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</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>/<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> (optional)<div class='sub-desc'><p>An <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">Ext.ComponentQuery</a> selector or <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>. If no selector is\nspecified, the first child will be returned.</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 href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> The matching descendant <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> (or <code>null</code> if no match was found).</p>\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.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-enable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-enable' class='name expandable'>enable</a>( <span class='pre'>[silent]</span> ) : <a href=\"#!/api/Ext.container.AbstractContainer\" rel=\"Ext.container.AbstractContainer\" class=\"docClass\">Ext.container.AbstractContainer</a><strong class='chainable signature' >chainable</strong><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Enable all immediate children that was previously disabled\nOverride enable because onEnable only gets called when ren...</div><div class='long'><p>Enable all immediate children that was previously disabled\nOverride enable because onEnable only gets called when rendered</p>\n\n<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><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.container.AbstractContainer\" rel=\"Ext.container.AbstractContainer\" class=\"docClass\">Ext.container.AbstractContainer</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-enable' rel='Ext.AbstractComponent-method-enable' class='docClass'>Ext.AbstractComponent.enable</a></p></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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-finishRenderChildren' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-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<p>Overrides: <a href='#!/api/Ext.util.Renderable-method-finishRenderChildren' rel='Ext.util.Renderable-method-finishRenderChildren' class='docClass'>Ext.util.Renderable.finishRenderChildren</a></p></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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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> : Mixed (optional)<div class='sub-desc'><p>If applicable, <code>true</code> to also select all the text in this component, or an array consisting of start and end (defaults to start) position of selection.</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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-getActiveGroup' 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.ux.GroupTabPanel'>Ext.ux.GroupTabPanel</span><br/><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel-method-getActiveGroup' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.ux.GroupTabPanel-method-getActiveGroup' class='name expandable'>getActiveGroup</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></div><div class='description'><div class='short'>Returns the root group item that is currently active inside this GroupTabPanel. ...</div><div class='long'><p>Returns the root group item that is currently active inside this GroupTabPanel.</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>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span><div class='sub-desc'><p>The currently active root group item</p>\n</div></li></ul></div></div></div><div id='method-getActiveTab' 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.ux.GroupTabPanel'>Ext.ux.GroupTabPanel</span><br/><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel-method-getActiveTab' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.ux.GroupTabPanel-method-getActiveTab' class='name expandable'>getActiveTab</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></div><div class='description'><div class='short'>Returns the item that is currently active inside this GroupTabPanel. ...</div><div class='long'><p>Returns the item that is currently active inside this GroupTabPanel.</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>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span><div class='sub-desc'><p>The currently active item</p>\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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-getChildByElement' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.Container' rel='Ext.container.Container' class='defined-in docClass'>Ext.container.Container</a><br/><a href='source/Container.html#Ext-container-Container-method-getChildByElement' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.Container-method-getChildByElement' class='name expandable'>getChildByElement</a>( <span class='pre'>el, deep</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Return the immediate child Component in which the passed element is located. ...</div><div class='long'><p>Return the immediate child Component in which the passed element is located.</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.Element</a>/HTMLElement/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The element to test (or ID of element).</p>\n</div></li><li><span class='pre'>deep</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p>If <code>true</code>, returns the deepest descendant Component which contains the passed element.</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 child item which contains the passed element.</p>\n</div></li></ul></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-getChildItemsToDisable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-getChildItemsToDisable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-getChildItemsToDisable' class='name expandable'>getChildItemsToDisable</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>[]<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Gets a list of child components to enable/disable when the container is\nenabled/disabled ...</div><div class='long'><p>Gets a list of child components to enable/disable when the container is\nenabled/disabled</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>Items to be enabled/disabled</p>\n</div></li></ul></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-getComponent' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-getComponent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-getComponent' class='name expandable'>getComponent</a>( <span class='pre'>comp</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Examines this container's items property and gets a direct child\ncomponent of this container. ...</div><div class='long'><p>Examines this container's <a href=\"#!/api/Ext.container.AbstractContainer-property-items\" rel=\"Ext.container.AbstractContainer-property-items\" class=\"docClass\">items</a> <strong>property</strong> and gets a direct child\ncomponent of this container.</p>\n <p>Available since: <b>2.3.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>comp</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>This parameter may be any of the following:</p>\n\n<ul>\n<li>a <strong>String</strong> : representing the <a href=\"#!/api/Ext.Component-cfg-itemId\" rel=\"Ext.Component-cfg-itemId\" class=\"docClass\">itemId</a>\nor <a href=\"#!/api/Ext.Component-cfg-id\" rel=\"Ext.Component-cfg-id\" class=\"docClass\">id</a> of the child component.</li>\n<li>a <strong>Number</strong> : representing the position of the child component\nwithin the <a href=\"#!/api/Ext.container.AbstractContainer-property-items\" rel=\"Ext.container.AbstractContainer-property-items\" class=\"docClass\">items</a> <strong>property</strong></li>\n</ul>\n\n\n<p>For additional information see <a href=\"#!/api/Ext.util.MixedCollection-method-get\" rel=\"Ext.util.MixedCollection-method-get\" class=\"docClass\">Ext.util.MixedCollection.get</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>The component (if found).</p>\n</div></li></ul></div></div></div><div id='method-getComponentId' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-getComponentId' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-getComponentId' class='name expandable'>getComponentId</a>( <span class='pre'>comp</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>used as the key lookup function for the items collection ...</div><div class='long'><ul>\n<li>used as the key lookup function for the items collection</li>\n</ul>\n\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>comp</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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-getContentTarget' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-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<p>Overrides: <a href='#!/api/Ext.Component-method-getContentTarget' rel='Ext.Component-method-getContentTarget' class='docClass'>Ext.Component.getContentTarget</a></p></div></div></div><div id='method-getDefaultContentTarget' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-getDefaultContentTarget' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-getDefaultContentTarget' class='name expandable'>getDefaultContentTarget</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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-getFocusEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-getFocusEl' class='name expandable'>getFocusEl</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Returns the focus holder element associated with this Container. ...</div><div class='long'><p>Returns the focus holder element associated with this Container. By default, this is the Container's target\nelement. Subclasses which use embedded focusable elements (such as Window and Button) should override this for use\nby the <a href=\"#!/api/Ext.container.AbstractContainer-method-focus\" rel=\"Ext.container.AbstractContainer-method-focus\" class=\"docClass\">focus</a> method.</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 focus holding element.</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-getFocusEl' rel='Ext.AbstractComponent-method-getFocusEl' class='docClass'>Ext.AbstractComponent.getFocusEl</a></p></div></div></div><div id='method-getFocusTask' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.html#Ext-Component-method-getFocusTask' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getFocusTask' class='name expandable'>getFocusTask</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-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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-getLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-getLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-getLayout' class='name expandable'>getLayout</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.layout.container.Container\" rel=\"Ext.layout.container.Container\" class=\"docClass\">Ext.layout.container.Container</a></div><div class='description'><div class='short'>Returns the layout instance currently associated with this Container. ...</div><div class='long'><p>Returns the <a href=\"#!/api/Ext.layout.container.Container\" rel=\"Ext.layout.container.Container\" class=\"docClass\">layout</a> instance currently associated with this Container.\nIf a layout has not been instantiated yet, that is done first</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.layout.container.Container\" rel=\"Ext.layout.container.Container\" class=\"docClass\">Ext.layout.container.Container</a></span><div class='sub-desc'><p>The layout</p>\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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-getRefItems' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-getRefItems' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-getRefItems' class='name expandable'>getRefItems</a>( <span class='pre'>deep</span> )<strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Used by ComponentQuery, child and down to retrieve all of the items\nwhich can potentially be considered a child of th...</div><div class='long'><p>Used by <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">ComponentQuery</a>, <a href=\"#!/api/Ext.container.AbstractContainer-method-child\" rel=\"Ext.container.AbstractContainer-method-child\" class=\"docClass\">child</a> and <a href=\"#!/api/Ext.container.AbstractContainer-method-down\" rel=\"Ext.container.AbstractContainer-method-down\" class=\"docClass\">down</a> to retrieve all of the items\nwhich can potentially be considered a child of this Container.</p>\n\n<p>This may be overriden by Components which have ownership of Components\nthat are not contained in the <a href=\"#!/api/Ext.container.AbstractContainer-property-items\" rel=\"Ext.container.AbstractContainer-property-items\" class=\"docClass\">items</a> collection.</p>\n\n<p>NOTE: IMPORTANT note for maintainers:\nItems are returned in tree traversal order. Each item is appended to the result array\nfollowed by the results of that child's getRefItems call.\nFloating child items are appended after internal child items.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>deep</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.Queryable-method-getRefItems' rel='Ext.Queryable-method-getRefItems' class='docClass'>Ext.Queryable.getRefItems</a></p></div></div></div><div id='method-getRefOwner' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-getRowClass' 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.ux.GroupTabPanel'>Ext.ux.GroupTabPanel</span><br/><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel-method-getRowClass' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.ux.GroupTabPanel-method-getRowClass' class='name expandable'>getRowClass</a>( <span class='pre'>node, rowIndex, rowParams, store</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'>node</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>rowIndex</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>rowParams</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>store</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-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'>[contentSize]</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\">Parameters</h3><ul><li><span class='pre'>contentSize</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>true to get the width/size minus borders and padding</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 containing the element's size:</p>\n<ul><li><span class='pre'>width</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'></div></li><li><span class='pre'>height</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'></div></li></ul></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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><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.ux.GroupTabPanel'>Ext.ux.GroupTabPanel</span><br/><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel-method-initComponent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.ux.GroupTabPanel-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.container.AbstractContainer-method-initComponent' rel='Ext.container.AbstractContainer-method-initComponent' class='docClass'>Ext.container.AbstractContainer.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-initItems' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-initItems' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-initItems' class='name expandable'>initItems</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-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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-insert' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-insert' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-insert' class='name expandable'>insert</a>( <span class='pre'>index, component</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Inserts a Component into this Container at a specified index. ...</div><div class='long'><p>Inserts a Component into this Container at a specified index. Fires the\n<a href=\"#!/api/Ext.container.AbstractContainer-event-beforeadd\" rel=\"Ext.container.AbstractContainer-event-beforeadd\" class=\"docClass\">beforeadd</a> event before inserting, then fires the <a href=\"#!/api/Ext.container.AbstractContainer-event-add\" rel=\"Ext.container.AbstractContainer-event-add\" class=\"docClass\">add</a>\nevent after the Component has been inserted.</p>\n <p>Available since: <b>2.3.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>index</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The index at which the Component will be inserted\ninto the Container's items collection</p>\n</div></li><li><span class='pre'>component</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The child Component to insert.</p>\n\n<p>Ext uses lazy rendering, and will only render the inserted Component should\nit become necessary.</p>\n\n<p>A Component config object may be passed in order to avoid the overhead of\nconstructing a real Component object if lazy rendering might mean that the\ninserted Component will not be rendered immediately. To take advantage of\nthis 'lazy instantiation', set the <a href=\"#!/api/Ext.Component-cfg-xtype\" rel=\"Ext.Component-cfg-xtype\" class=\"docClass\">Ext.Component.xtype</a> config\nproperty to the registered type of the Component wanted.</p>\n\n<p>For a list of all available xtypes, see <a href=\"#!/api/Ext.enums.Widget\" rel=\"Ext.enums.Widget\" class=\"docClass\">Ext.enums.Widget</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>component The Component (or config object) that was\ninserted with the Container's default config values applied.</p>\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-isAncestor' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-isAncestor' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-isAncestor' class='name expandable'>isAncestor</a>( <span class='pre'>possibleDescendant</span> )</div><div class='description'><div class='short'>Determines whether this Container is an ancestor of the passed Component. ...</div><div class='long'><p>Determines whether <strong>this Container</strong> is an ancestor of the passed Component.\nThis will return <code>true</code> if the passed Component is anywhere within the subtree\nbeneath this Container.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>possibleDescendant</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The Component to test for presence\nwithin this Container's subtree.</p>\n</div></li></ul></div></div></div><div id='method-isContainedFloater' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-lookupComponent' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-lookupComponent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-lookupComponent' class='name expandable'>lookupComponent</a>( <span class='pre'>comp</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'>comp</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-makeFloating' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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'>msg, msgCls, elHeight</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'>msg</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>msgCls</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>elHeight</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-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.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-move' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-move' class='name expandable'>move</a>( <span class='pre'>fromIdx, toIdx</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Moves a Component within the Container ...</div><div class='long'><p>Moves a Component within the Container</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>fromIdx</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The index/component to move.</p>\n</div></li><li><span class='pre'>toIdx</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The new index for the 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>component The Component that was moved.</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-move' rel='Ext.util.Positionable-method-move' class='docClass'>Ext.util.Positionable.move</a></p></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-nextChild' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-nextChild' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-nextChild' class='name expandable'>nextChild</a>( <span class='pre'>child, selector</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'>child</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>selector</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-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-onAdd' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-onAdd' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-onAdd' class='name expandable'>onAdd</a>( <span class='pre'>component, position</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>This method is invoked after a new Component has been added. ...</div><div class='long'><p>This method is invoked after a new Component has been added. It\nis passed the Component which has been added. This method may\nbe used to update any internal structure which may depend upon\nthe state of the child items.</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'>component</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'>position</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-onAdded' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-onBeforeAdd' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-onBeforeAdd' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-onBeforeAdd' class='name expandable'>onBeforeAdd</a>( <span class='pre'>item</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>This method is invoked before adding a new child Component. ...</div><div class='long'><p>This method is invoked before adding a new child Component. It\nis passed the new Component, and may be used to modify the\nComponent, or prepare the Container in some way. Returning\nfalse aborts the add operation.</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'>item</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li></ul></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='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Invoked when this component has first achieved size. ...</div><div class='long'><p>Invoked when this component has first achieved size. Occurs after the\n<a href=\"#!/api/Ext.AbstractComponent-cfg-componentLayout\" rel=\"Ext.AbstractComponent-cfg-componentLayout\" class=\"docClass\">componentLayout</a> has completed its initial run.</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 of this component</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 height of this component</p>\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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-onMove' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-onMove' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-onMove' class='name expandable'>onMove</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-onNodeSelect' 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.ux.GroupTabPanel'>Ext.ux.GroupTabPanel</span><br/><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel-method-onNodeSelect' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.ux.GroupTabPanel-method-onNodeSelect' class='name expandable'>onNodeSelect</a>( <span class='pre'>selModel, node</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Node selection listener. ...</div><div class='long'><p>Node selection listener.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>selModel</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>node</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.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-onPosition' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-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><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-onPosition' rel='Ext.AbstractComponent-method-onPosition' class='docClass'>Ext.AbstractComponent.onPosition</a></p></div></div></div><div id='method-onRemove' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-onRemove' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-onRemove' class='name expandable'>onRemove</a>( <span class='pre'>component, autoDestroy</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>This method is invoked after a new Component has been\nremoved. ...</div><div class='long'><p>This method is invoked after a new Component has been\nremoved. It is passed the Component which has been\nremoved. This method may be used to update any internal\nstructure which may depend upon the state of the child items.</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'>component</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'>autoDestroy</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-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.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-onResize' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-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><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-onResize' rel='Ext.AbstractComponent-method-onResize' class='docClass'>Ext.AbstractComponent.onResize</a></p></div></div></div><div id='method-onShow' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-event-show\" rel=\"Ext.Component-event-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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-prepareItems' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-prepareItems' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-prepareItems' class='name expandable'>prepareItems</a>( <span class='pre'>items, applyDefaults</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'>items</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>applyDefaults</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-prevChild' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-prevChild' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-prevChild' class='name expandable'>prevChild</a>( <span class='pre'>child, selector</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'>child</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>selector</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-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-query' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Queryable' rel='Ext.Queryable' class='defined-in docClass'>Ext.Queryable</a><br/><a href='source/Queryable.html#Ext-Queryable-method-query' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Queryable-method-query' class='name expandable'>query</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'>Retrieves all descendant components which match the passed selector. ...</div><div class='long'><p>Retrieves all descendant components which match the passed selector.\nExecutes an <a href=\"#!/api/Ext.ComponentQuery-method-query\" rel=\"Ext.ComponentQuery-method-query\" class=\"docClass\">Ext.ComponentQuery.query</a> using this container as its root.</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>Selector complying to an <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">Ext.ComponentQuery</a> selector.\nIf no selector is specified all items will be returned.</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>Components which matched the selector</p>\n</div></li></ul></div></div></div><div id='method-queryBy' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Queryable' rel='Ext.Queryable' class='defined-in docClass'>Ext.Queryable</a><br/><a href='source/Queryable.html#Ext-Queryable-method-queryBy' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Queryable-method-queryBy' class='name expandable'>queryBy</a>( <span class='pre'>fn, [scope]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>[]</div><div class='description'><div class='short'>Retrieves all descendant components which match the passed function. ...</div><div class='long'><p>Retrieves all descendant components which match the passed function.\nThe function should return false for components that are to be\nexcluded from the selection.</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 matcher function. It will be called with a single argument,\nthe component being tested.</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 in which to run the function. If not specified,\nit will default to the active 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>Components matched by the passed function</p>\n</div></li></ul></div></div></div><div id='method-queryById' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Queryable' rel='Ext.Queryable' class='defined-in docClass'>Ext.Queryable</a><br/><a href='source/Queryable.html#Ext-Queryable-method-queryById' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Queryable-method-queryById' class='name expandable'>queryById</a>( <span class='pre'>id</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Finds a component at any level under this container matching the id/itemId. ...</div><div class='long'><p>Finds a component at any level under this container matching the id/itemId.\nThis is a shorthand for calling ct.down('#' + id);</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>id</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The id to find</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 matching id, null if not found</p>\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-remove' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-remove' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-remove' class='name expandable'>remove</a>( <span class='pre'>component, [autoDestroy]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Removes a component from this container. ...</div><div class='long'><p>Removes a component from this container. Fires the <a href=\"#!/api/Ext.container.AbstractContainer-event-beforeremove\" rel=\"Ext.container.AbstractContainer-event-beforeremove\" class=\"docClass\">beforeremove</a> event\nbefore removing, then fires the <a href=\"#!/api/Ext.container.AbstractContainer-event-remove\" rel=\"Ext.container.AbstractContainer-event-remove\" class=\"docClass\">remove</a> event after the component has\nbeen removed.</p>\n <p>Available since: <b>2.3.0</b></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/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The component reference or id to remove.</p>\n</div></li><li><span class='pre'>autoDestroy</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>True to automatically invoke the removed Component's\n<a href=\"#!/api/Ext.Component-method-destroy\" rel=\"Ext.Component-method-destroy\" class=\"docClass\">Ext.Component.destroy</a> function.</p>\n\n<p>Defaults to the value of this Container's <a href=\"#!/api/Ext.container.AbstractContainer-cfg-autoDestroy\" rel=\"Ext.container.AbstractContainer-cfg-autoDestroy\" class=\"docClass\">autoDestroy</a> config.</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>component The Component that was removed.</p>\n</div></li></ul></div></div></div><div id='method-removeAll' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-removeAll' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-removeAll' class='name expandable'>removeAll</a>( <span class='pre'>[autoDestroy]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>[]</div><div class='description'><div class='short'>Removes all components from this container. ...</div><div class='long'><p>Removes all components from this container.</p>\n <p>Available since: <b>2.3.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>autoDestroy</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>True to automatically invoke the removed\nComponent's <a href=\"#!/api/Ext.Component-method-destroy\" rel=\"Ext.Component-method-destroy\" class=\"docClass\">Ext.Component.destroy</a> function.\nDefaults to the value of this Container's <a href=\"#!/api/Ext.container.AbstractContainer-cfg-autoDestroy\" rel=\"Ext.container.AbstractContainer-cfg-autoDestroy\" class=\"docClass\">autoDestroy</a> config.</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>Array of the removed components</p>\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-repositionFloatingItems' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-repositionFloatingItems' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-repositionFloatingItems' class='name expandable'>repositionFloatingItems</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-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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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-setActiveGroup' 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.ux.GroupTabPanel'>Ext.ux.GroupTabPanel</span><br/><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel-method-setActiveGroup' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.ux.GroupTabPanel-method-setActiveGroup' class='name expandable'>setActiveGroup</a>( <span class='pre'>cmp</span> )</div><div class='description'><div class='short'>Makes the given group active ...</div><div class='long'><p>Makes the given group active</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>cmp</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The root component to make active.</p>\n</div></li></ul></div></div></div><div id='method-setActiveTab' 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.ux.GroupTabPanel'>Ext.ux.GroupTabPanel</span><br/><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel-method-setActiveTab' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.ux.GroupTabPanel-method-setActiveTab' class='name expandable'>setActiveTab</a>( <span class='pre'>cmp</span> )</div><div class='description'><div class='short'>Makes the given component active (makes it the visible card in the GroupTabPanel's CardLayout) ...</div><div class='long'><p>Makes the given component active (makes it the visible card in the GroupTabPanel's CardLayout)</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>cmp</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The component to make active</p>\n</div></li></ul></div></div></div><div id='method-setAutoScroll' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><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-setLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-setLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-method-setLayout' class='name expandable'>setLayout</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-setLoading' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><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.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-method-setupRenderTpl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-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><p>Overrides: <a href='#!/api/Ext.util.Renderable-method-setupRenderTpl' rel='Ext.util.Renderable-method-setupRenderTpl' class='docClass'>Ext.util.Renderable.setupRenderTpl</a></p></div></div></div><div id='method-show' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 selector or component. ...</div><div class='long'><p>Navigates up the ownership hierarchy searching for an ancestor Container which matches any passed 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 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 the 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-updateBox' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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 inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Component' rel='Ext.Component' class='defined-in docClass'>Ext.Component</a><br/><a href='source/Component6.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\n<p><strong>Note</strong> This event is only fired if this Component is a child of a <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a>\nthat uses <a href=\"#!/api/Ext.layout.container.Card\" rel=\"Ext.layout.container.Card\" class=\"docClass\">Ext.layout.container.Card</a> as it's layout or this Component is a floating Component.</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-add' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-event-add' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-event-add' class='name expandable'>add</a>( <span class='pre'>this, component, index, eOpts</span> )</div><div class='description'><div class='short'>Fires after any Ext.Component is added or inserted into the container. ...</div><div class='long'><p>Fires after any <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> is added or inserted into the container.</p>\n\n<p><strong>This event bubbles:</strong> 'add' will also be fired when Component is added to any of\nthe child containers or their childern or ...</p>\n <p>Available since: <b>2.3.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a><div class='sub-desc'>\n</div></li><li><span class='pre'>component</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The component that was added</p>\n</div></li><li><span class='pre'>index</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The index at which the component was added to the container's items collection</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-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-afterlayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-event-afterlayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-event-afterlayout' class='name expandable'>afterlayout</a>( <span class='pre'>this, layout, eOpts</span> )</div><div class='description'><div class='short'>Fires when the components in this container are arranged by the associated layout manager. ...</div><div class='long'><p>Fires when the components in this container are arranged by the associated layout manager.</p>\n <p>Available since: <b>2.3.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a><div class='sub-desc'>\n</div></li><li><span class='pre'>layout</span> : <a href=\"#!/api/Ext.layout.container.Container\" rel=\"Ext.layout.container.Container\" class=\"docClass\">Ext.layout.container.Container</a><div class='sub-desc'><p>The ContainerLayout implementation for this container</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\n<p><strong>Note</strong> This event is only fired if this Component is a child of a <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a>\nthat uses <a href=\"#!/api/Ext.layout.container.Card\" rel=\"Ext.layout.container.Card\" class=\"docClass\">Ext.layout.container.Card</a> as it's layout.</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-beforeadd' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-event-beforeadd' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-event-beforeadd' class='name expandable'>beforeadd</a>( <span class='pre'>this, component, index, eOpts</span> )</div><div class='description'><div class='short'>Fires before any Ext.Component is added or inserted into the container. ...</div><div class='long'><p>Fires before any <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> is added or inserted into the container.\nA handler can return false to cancel the add.</p>\n <p>Available since: <b>2.3.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a><div class='sub-desc'>\n</div></li><li><span class='pre'>component</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The component being added</p>\n</div></li><li><span class='pre'>index</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The index at which the component will be added to the container's items collection</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-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\n<p><strong>Note</strong> This event is only fired if this Component is a child of a <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a>\nthat uses <a href=\"#!/api/Ext.layout.container.Card\" rel=\"Ext.layout.container.Card\" class=\"docClass\">Ext.layout.container.Card</a> as it's layout.</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-beforegroupchange' 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.ux.GroupTabPanel'>Ext.ux.GroupTabPanel</span><br/><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel-event-beforegroupchange' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.ux.GroupTabPanel-event-beforegroupchange' class='name expandable'>beforegroupchange</a>( <span class='pre'>grouptabPanel, newGroup, oldGroup, eOpts</span> )</div><div class='description'><div class='short'>Fires before a group change (activated by setActiveGroup). ...</div><div class='long'><p>Fires before a group change (activated by <a href=\"#!/api/Ext.ux.GroupTabPanel-method-setActiveGroup\" rel=\"Ext.ux.GroupTabPanel-method-setActiveGroup\" class=\"docClass\">setActiveGroup</a>). Return false in any listener to cancel\nthe groupchange</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>grouptabPanel</span> : <a href=\"#!/api/Ext.ux.GroupTabPanel\" rel=\"Ext.ux.GroupTabPanel\" class=\"docClass\">Ext.ux.GroupTabPanel</a><div class='sub-desc'><p>The GroupTabPanel</p>\n</div></li><li><span class='pre'>newGroup</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The root group card that is about to be activated</p>\n</div></li><li><span class='pre'>oldGroup</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The root group card that is currently active</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-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-beforeremove' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-event-beforeremove' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-event-beforeremove' class='name expandable'>beforeremove</a>( <span class='pre'>this, component, eOpts</span> )</div><div class='description'><div class='short'>Fires before any Ext.Component is removed from the container. ...</div><div class='long'><p>Fires before any <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> is removed from the container. A handler can return\nfalse to cancel the remove.</p>\n <p>Available since: <b>2.3.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a><div class='sub-desc'>\n</div></li><li><span class='pre'>component</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The component being removed</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-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-beforetabchange' 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.ux.GroupTabPanel'>Ext.ux.GroupTabPanel</span><br/><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel-event-beforetabchange' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.ux.GroupTabPanel-event-beforetabchange' class='name expandable'>beforetabchange</a>( <span class='pre'>grouptabPanel, newCard, oldCard, eOpts</span> )</div><div class='description'><div class='short'>Fires before a tab change (activated by setActiveTab). ...</div><div class='long'><p>Fires before a tab change (activated by <a href=\"#!/api/Ext.ux.GroupTabPanel-method-setActiveTab\" rel=\"Ext.ux.GroupTabPanel-method-setActiveTab\" class=\"docClass\">setActiveTab</a>). Return false in any listener to cancel\nthe tabchange</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>grouptabPanel</span> : <a href=\"#!/api/Ext.ux.GroupTabPanel\" rel=\"Ext.ux.GroupTabPanel\" class=\"docClass\">Ext.ux.GroupTabPanel</a><div class='sub-desc'><p>The GroupTabPanel</p>\n</div></li><li><span class='pre'>newCard</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The card that is about to be activated</p>\n</div></li><li><span class='pre'>oldCard</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The card that is currently active</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\n<p><strong>Note</strong> This event is only fired if this Component is a child of a <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a>\nthat uses <a href=\"#!/api/Ext.layout.container.Card\" rel=\"Ext.layout.container.Card\" class=\"docClass\">Ext.layout.container.Card</a> as it's layout or this Component is a floating Component.</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-groupchange' 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.ux.GroupTabPanel'>Ext.ux.GroupTabPanel</span><br/><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel-event-groupchange' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.ux.GroupTabPanel-event-groupchange' class='name expandable'>groupchange</a>( <span class='pre'>grouptabPanel, newGroup, oldGroup, eOpts</span> )</div><div class='description'><div class='short'>Fires when a new group has been activated (activated by setActiveGroup). ...</div><div class='long'><p>Fires when a new group has been activated (activated by <a href=\"#!/api/Ext.ux.GroupTabPanel-method-setActiveGroup\" rel=\"Ext.ux.GroupTabPanel-method-setActiveGroup\" class=\"docClass\">setActiveGroup</a>).</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>grouptabPanel</span> : <a href=\"#!/api/Ext.ux.GroupTabPanel\" rel=\"Ext.ux.GroupTabPanel\" class=\"docClass\">Ext.ux.GroupTabPanel</a><div class='sub-desc'><p>The GroupTabPanel</p>\n</div></li><li><span class='pre'>newGroup</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The newly activated root group item</p>\n</div></li><li><span class='pre'>oldGroup</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The previously active root group item</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-remove' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='defined-in docClass'>Ext.container.AbstractContainer</a><br/><a href='source/AbstractContainer.html#Ext-container-AbstractContainer-event-remove' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.container.AbstractContainer-event-remove' class='name expandable'>remove</a>( <span class='pre'>this, component, eOpts</span> )</div><div class='description'><div class='short'>Fires after any Ext.Component is removed from the container. ...</div><div class='long'><p>Fires after any <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> is removed from the container.</p>\n\n<p><strong>This event bubbles:</strong> 'remove' will also be fired when Component is removed from any of\nthe child containers or their children or ...</p>\n <p>Available since: <b>2.3.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a><div class='sub-desc'>\n</div></li><li><span class='pre'>component</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The component that was removed</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 id='event-tabchange' 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.ux.GroupTabPanel'>Ext.ux.GroupTabPanel</span><br/><a href='source/GroupTabPanel.html#Ext-ux-GroupTabPanel-event-tabchange' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.ux.GroupTabPanel-event-tabchange' class='name expandable'>tabchange</a>( <span class='pre'>grouptabPanel, newCard, oldCard, eOpts</span> )</div><div class='description'><div class='short'>Fires when a new tab has been activated (activated by setActiveTab). ...</div><div class='long'><p>Fires when a new tab has been activated (activated by <a href=\"#!/api/Ext.ux.GroupTabPanel-method-setActiveTab\" rel=\"Ext.ux.GroupTabPanel-method-setActiveTab\" class=\"docClass\">setActiveTab</a>).</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>grouptabPanel</span> : <a href=\"#!/api/Ext.ux.GroupTabPanel\" rel=\"Ext.ux.GroupTabPanel\" class=\"docClass\">Ext.ux.GroupTabPanel</a><div class='sub-desc'><p>The GroupTabPanel</p>\n</div></li><li><span class='pre'>newCard</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The newly activated item</p>\n</div></li><li><span class='pre'>oldCard</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'><p>The previously active item</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","Ext.Component","Ext.container.AbstractContainer","Ext.container.Container"],"meta":{"author":["Nicolas Ferrero"]},"code_type":"ext_define","requires":["Ext.tree.Panel","Ext.ux.GroupTabRenderer"],"html_meta":{"author":null},"statics":{"property":[{"tagname":"property","owner":"Ext.Base","meta":{"static":true,"private":true},"name":"$onExtended","id":"static-property-S-onExtended"}],"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":"GroupTabPanel.html#Ext-ux-GroupTabPanel","filename":"GroupTabPanel.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.container.AbstractContainer","meta":{"private":true},"name":"ariaRole","id":"property-ariaRole"},{"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.container.AbstractContainer","meta":{"private":true},"name":"isContainer","id":"property-isContainer"},{"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.Queryable","meta":{"private":true},"name":"isQueryable","id":"property-isQueryable"},{"tagname":"property","owner":"Ext.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"items","id":"property-items"},{"tagname":"property","owner":"Ext.container.AbstractContainer","meta":{"private":true},"name":"layoutCounter","id":"property-layoutCounter"},{"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.AbstractComponent","meta":{"private":true},"name":"rootCls","id":"property-rootCls"},{"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.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.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"activeItem","id":"cfg-activeItem"},{"tagname":"cfg","owner":"Ext.container.Container","meta":{},"name":"anchorSize","id":"cfg-anchorSize"},{"tagname":"cfg","owner":"Ext.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"autoDestroy","id":"cfg-autoDestroy"},{"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.ux.GroupTabPanel","meta":{},"name":"baseCls","id":"cfg-baseCls"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"border","id":"cfg-border"},{"tagname":"cfg","owner":"Ext.container.AbstractContainer","meta":{"since":"3.4.0"},"name":"bubbleEvents","id":"cfg-bubbleEvents"},{"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.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"defaultType","id":"cfg-defaultType"},{"tagname":"cfg","owner":"Ext.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"defaults","id":"cfg-defaults"},{"tagname":"cfg","owner":"Ext.container.AbstractContainer","meta":{},"name":"detachOnRemove","id":"cfg-detachOnRemove"},{"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.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"items","id":"cfg-items"},{"tagname":"cfg","owner":"Ext.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"layout","id":"cfg-layout"},{"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.container.AbstractContainer","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.container.AbstractContainer","meta":{},"name":"suspendLayout","id":"cfg-suspendLayout"},{"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":"weight","id":"cfg-weight"},{"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.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"add","id":"method-add"},{"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.container.AbstractContainer","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.container.AbstractContainer","meta":{"protected":true,"template":true},"name":"afterLayout","id":"method-afterLayout"},{"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.container.AbstractContainer","meta":{"private":true},"name":"applyDefaults","id":"method-applyDefaults"},{"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.container.AbstractContainer","meta":{"private":true},"name":"applyTargetCls","id":"method-applyTargetCls"},{"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.container.AbstractContainer","meta":{"since":"2.3.0","template":true,"protected":true,"private":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.container.AbstractContainer","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":{"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.container.AbstractContainer","meta":{"chainable":true,"since":"2.3.0"},"name":"cascade","id":"method-cascade"},{"tagname":"method","owner":"Ext.util.Floating","meta":{},"name":"center","id":"method-center"},{"tagname":"method","owner":"Ext.Queryable","meta":{},"name":"child","id":"method-child"},{"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.container.AbstractContainer","meta":{},"name":"contains","id":"method-contains"},{"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.ux.GroupTabPanel","meta":{"private":true},"name":"createTreeStore","id":"method-createTreeStore"},{"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.container.AbstractContainer","meta":{"private":true},"name":"detachComponent","id":"method-detachComponent"},{"tagname":"method","owner":"Ext.container.AbstractContainer","meta":{"chainable":true,"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.container.AbstractContainer","meta":{"chainable":true,"since":"2.3.0"},"name":"doLayout","id":"method-doLayout"},{"tagname":"method","owner":"Ext.container.AbstractContainer","meta":{"private":true},"name":"doRemove","id":"method-doRemove"},{"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.Queryable","meta":{},"name":"down","id":"method-down"},{"tagname":"method","owner":"Ext.container.AbstractContainer","meta":{"chainable":true,"since":"1.1.0","private":true},"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.container.AbstractContainer","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.ux.GroupTabPanel","meta":{},"name":"getActiveGroup","id":"method-getActiveGroup"},{"tagname":"method","owner":"Ext.ux.GroupTabPanel","meta":{},"name":"getActiveTab","id":"method-getActiveTab"},{"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.container.Container","meta":{},"name":"getChildByElement","id":"method-getChildByElement"},{"tagname":"method","owner":"Ext.util.ElementContainer","meta":{"private":true},"name":"getChildEls","id":"method-getChildEls"},{"tagname":"method","owner":"Ext.container.AbstractContainer","meta":{"private":true},"name":"getChildItemsToDisable","id":"method-getChildItemsToDisable"},{"tagname":"method","owner":"Ext.util.ElementContainer","meta":{"private":true},"name":"getClassChildEls","id":"method-getClassChildEls"},{"tagname":"method","owner":"Ext.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"getComponent","id":"method-getComponent"},{"tagname":"method","owner":"Ext.container.AbstractContainer","meta":{"private":true},"name":"getComponentId","id":"method-getComponentId"},{"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.container.AbstractContainer","meta":{"private":true},"name":"getContentTarget","id":"method-getContentTarget"},{"tagname":"method","owner":"Ext.container.AbstractContainer","meta":{"private":true},"name":"getDefaultContentTarget","id":"method-getDefaultContentTarget"},{"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.container.AbstractContainer","meta":{"private":true},"name":"getFocusEl","id":"method-getFocusEl"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"getFocusTask","id":"method-getFocusTask"},{"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.container.AbstractContainer","meta":{},"name":"getLayout","id":"method-getLayout"},{"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.container.AbstractContainer","meta":{"protected":true},"name":"getRefItems","id":"method-getRefItems"},{"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.ux.GroupTabPanel","meta":{"private":true},"name":"getRowClass","id":"method-getRowClass"},{"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.ux.GroupTabPanel","meta":{"since":"1.1.0","template":true,"protected":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.container.AbstractContainer","meta":{"private":true},"name":"initItems","id":"method-initItems"},{"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.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"insert","id":"method-insert"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"is","id":"method-is"},{"tagname":"method","owner":"Ext.container.AbstractContainer","meta":{},"name":"isAncestor","id":"method-isAncestor"},{"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.container.AbstractContainer","meta":{"private":true},"name":"lookupComponent","id":"method-lookupComponent"},{"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.container.AbstractContainer","meta":{},"name":"move","id":"method-move"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"mun","id":"method-mun"},{"tagname":"method","owner":"Ext.container.AbstractContainer","meta":{"private":true},"name":"nextChild","id":"method-nextChild"},{"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.container.AbstractContainer","meta":{"protected":true,"template":true},"name":"onAdd","id":"method-onAdd"},{"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.container.AbstractContainer","meta":{"protected":true,"template":true},"name":"onBeforeAdd","id":"method-onBeforeAdd"},{"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":{"protected":true,"template":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.container.AbstractContainer","meta":{"private":true},"name":"onMove","id":"method-onMove"},{"tagname":"method","owner":"Ext.ux.GroupTabPanel","meta":{"private":true},"name":"onNodeSelect","id":"method-onNodeSelect"},{"tagname":"method","owner":"Ext.container.AbstractContainer","meta":{"template":true,"protected":true},"name":"onPosition","id":"method-onPosition"},{"tagname":"method","owner":"Ext.container.AbstractContainer","meta":{"protected":true,"template":true},"name":"onRemove","id":"method-onRemove"},{"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.container.AbstractContainer","meta":{"template":true,"protected":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.container.AbstractContainer","meta":{"private":true},"name":"prepareItems","id":"method-prepareItems"},{"tagname":"method","owner":"Ext.container.AbstractContainer","meta":{"private":true},"name":"prevChild","id":"method-prevChild"},{"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.Queryable","meta":{},"name":"query","id":"method-query"},{"tagname":"method","owner":"Ext.Queryable","meta":{},"name":"queryBy","id":"method-queryBy"},{"tagname":"method","owner":"Ext.Queryable","meta":{},"name":"queryById","id":"method-queryById"},{"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.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"remove","id":"method-remove"},{"tagname":"method","owner":"Ext.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"removeAll","id":"method-removeAll"},{"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.container.AbstractContainer","meta":{"private":true},"name":"repositionFloatingItems","id":"method-repositionFloatingItems"},{"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.ux.GroupTabPanel","meta":{},"name":"setActiveGroup","id":"method-setActiveGroup"},{"tagname":"method","owner":"Ext.ux.GroupTabPanel","meta":{},"name":"setActiveTab","id":"method-setActiveTab"},{"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.container.AbstractContainer","meta":{"private":true},"name":"setLayout","id":"method-setLayout"},{"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.container.AbstractContainer","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.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.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"add","id":"event-add"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"3.4.0"},"name":"added","id":"event-added"},{"tagname":"event","owner":"Ext.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"afterlayout","id":"event-afterlayout"},{"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.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"beforeadd","id":"event-beforeadd"},{"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.ux.GroupTabPanel","meta":{},"name":"beforegroupchange","id":"event-beforegroupchange"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"beforehide","id":"event-beforehide"},{"tagname":"event","owner":"Ext.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"beforeremove","id":"event-beforeremove"},{"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.ux.GroupTabPanel","meta":{},"name":"beforetabchange","id":"event-beforetabchange"},{"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.ux.GroupTabPanel","meta":{},"name":"groupchange","id":"event-groupchange"},{"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.container.AbstractContainer","meta":{"since":"2.3.0"},"name":"remove","id":"event-remove"},{"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"},{"tagname":"event","owner":"Ext.ux.GroupTabPanel","meta":{},"name":"tabchange","id":"event-tabchange"}],"css_mixin":[]},"inheritable":null,"private":null,"component":true,"name":"Ext.ux.GroupTabPanel","singleton":false,"override":null,"inheritdoc":null,"id":"class-Ext.ux.GroupTabPanel","mixins":[],"mixedInto":[]});
Libraries/Storage/AsyncStorage.js
CodeLinkIO/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule AsyncStorage * @noflow * @flow-weak * @jsdoc */ 'use strict'; const NativeModules = require('NativeModules'); // Use RocksDB if available, then SQLite, then file storage. const RCTAsyncStorage = NativeModules.AsyncRocksDBStorage || NativeModules.AsyncSQLiteDBStorage || NativeModules.AsyncLocalStorage; /** * @class * @description * `AsyncStorage` is a simple, unencrypted, asynchronous, persistent, key-value storage * system that is global to the app. It should be used instead of LocalStorage. * * It is recommended that you use an abstraction on top of `AsyncStorage` * instead of `AsyncStorage` directly for anything more than light usage since * it operates globally. * * On iOS, `AsyncStorage` is backed by native code that stores small values in a * serialized dictionary and larger values in separate files. On Android, * `AsyncStorage` will use either [RocksDB](http://rocksdb.org/) or SQLite * based on what is available. * * The `AsyncStorage` JavaScript code is a simple facade that provides a clear * JavaScript API, real `Error` objects, and simple non-multi functions. Each * method in the API returns a `Promise` object. * * Persisting data: * ``` * try { * await AsyncStorage.setItem('@MySuperStore:key', 'I like to save it.'); * } catch (error) { * // Error saving data * } * ``` * * Fetching data: * ``` * try { * const value = await AsyncStorage.getItem('@MySuperStore:key'); * if (value !== null){ * // We have data!! * console.log(value); * } * } catch (error) { * // Error retrieving data * } * ``` */ var AsyncStorage = { _getRequests: ([]: Array<any>), _getKeys: ([]: Array<string>), _immediate: (null: ?number), /** * Fetches an item for a `key` and invokes a callback upon completion. * Returns a `Promise` object. * @param key Key of the item to fetch. * @param callback Function that will be called with a result if found or * any error. * @returns A `Promise` object. */ getItem: function( key: string, callback?: ?(error: ?Error, result: ?string) => void ): Promise { return new Promise((resolve, reject) => { RCTAsyncStorage.multiGet([key], function(errors, result) { // Unpack result to get value from [[key,value]] var value = (result && result[0] && result[0][1]) ? result[0][1] : null; var errs = convertErrors(errors); callback && callback(errs && errs[0], value); if (errs) { reject(errs[0]); } else { resolve(value); } }); }); }, /** * Sets the value for a `key` and invokes a callback upon completion. * Returns a `Promise` object. * @param key Key of the item to set. * @param value Value to set for the `key`. * @param callback Function that will be called with any error. * @returns A `Promise` object. */ setItem: function( key: string, value: string, callback?: ?(error: ?Error) => void ): Promise { return new Promise((resolve, reject) => { RCTAsyncStorage.multiSet([[key,value]], function(errors) { var errs = convertErrors(errors); callback && callback(errs && errs[0]); if (errs) { reject(errs[0]); } else { resolve(null); } }); }); }, /** * Removes an item for a `key` and invokes a callback upon completion. * Returns a `Promise` object. * @param key Key of the item to remove. * @param callback Function that will be called with any error. * @returns A `Promise` object. */ removeItem: function( key: string, callback?: ?(error: ?Error) => void ): Promise { return new Promise((resolve, reject) => { RCTAsyncStorage.multiRemove([key], function(errors) { var errs = convertErrors(errors); callback && callback(errs && errs[0]); if (errs) { reject(errs[0]); } else { resolve(null); } }); }); }, /** * Merges an existing `key` value with an input value, assuming both values * are stringified JSON. Returns a `Promise` object. * * **NOTE:** This is not supported by all native implementations. * * @param key Key of the item to modify. * @param value New value to merge for the `key`. * @param callback Function that will be called with any error. * @returns A `Promise` object. * * @example <caption>Example</caption> * let UID123_object = { * name: 'Chris', * age: 30, * traits: {hair: 'brown', eyes: 'brown'}, * }; * // You only need to define what will be added or updated * let UID123_delta = { * age: 31, * traits: {eyes: 'blue', shoe_size: 10} * }; * * AsyncStorage.setItem('UID123', JSON.stringify(UID123_object), () => { * AsyncStorage.mergeItem('UID123', JSON.stringify(UID123_delta), () => { * AsyncStorage.getItem('UID123', (err, result) => { * console.log(result); * }); * }); * }); * * // Console log result: * // => {'name':'Chris','age':31,'traits': * // {'shoe_size':10,'hair':'brown','eyes':'blue'}} */ mergeItem: function( key: string, value: string, callback?: ?(error: ?Error) => void ): Promise { return new Promise((resolve, reject) => { RCTAsyncStorage.multiMerge([[key,value]], function(errors) { var errs = convertErrors(errors); callback && callback(errs && errs[0]); if (errs) { reject(errs[0]); } else { resolve(null); } }); }); }, /** * Erases *all* `AsyncStorage` for all clients, libraries, etc. You probably * don't want to call this; use `removeItem` or `multiRemove` to clear only * your app's keys. Returns a `Promise` object. * @param callback Function that will be called with any error. * @returns A `Promise` object. */ clear: function(callback?: ?(error: ?Error) => void): Promise { return new Promise((resolve, reject) => { RCTAsyncStorage.clear(function(error) { callback && callback(convertError(error)); if (error && convertError(error)){ reject(convertError(error)); } else { resolve(null); } }); }); }, /** * Gets *all* keys known to your app; for all callers, libraries, etc. * Returns a `Promise` object. * @param callback Function that will be called the keys found and any error. * @returns A `Promise` object. * * Example: see the `multiGet` example. */ getAllKeys: function(callback?: ?(error: ?Error, keys: ?Array<string>) => void): Promise { return new Promise((resolve, reject) => { RCTAsyncStorage.getAllKeys(function(error, keys) { callback && callback(convertError(error), keys); if (error) { reject(convertError(error)); } else { resolve(keys); } }); }); }, /** * The following batched functions are useful for executing a lot of * operations at once, allowing for native optimizations and provide the * convenience of a single callback after all operations are complete. * * These functions return arrays of errors, potentially one for every key. * For key-specific errors, the Error object will have a key property to * indicate which key caused the error. */ /** Flushes any pending requests using a single batch call to get the data. */ flushGetRequests: function(): void { const getRequests = this._getRequests; const getKeys = this._getKeys; this._getRequests = []; this._getKeys = []; RCTAsyncStorage.multiGet(getKeys, function(errors, result) { // Even though the runtime complexity of this is theoretically worse vs if we used a map, // it's much, much faster in practice for the data sets we deal with (we avoid // allocating result pair arrays). This was heavily benchmarked. // // Is there a way to avoid using the map but fix the bug in this breaking test? // https://github.com/facebook/react-native/commit/8dd8ad76579d7feef34c014d387bf02065692264 const map = {}; result && result.forEach(([key, value]) => { map[key] = value; return value; }); const reqLength = getRequests.length; for (let i = 0; i < reqLength; i++) { const request = getRequests[i]; const requestKeys = request.keys; const requestResult = requestKeys.map(key => [key, map[key]]); request.callback && request.callback(null, requestResult); request.resolve && request.resolve(requestResult); } }); }, /** * This allows you to batch the fetching of items given an array of `key` * inputs. Your callback will be invoked with an array of corresponding * key-value pairs found: * * ``` * multiGet(['k1', 'k2'], cb) -> cb([['k1', 'val1'], ['k2', 'val2']]) * ``` * * The method returns a `Promise` object. * * @param keys Array of key for the items to get. * @param callback Function that will be called with a key-value array of * the results, plus an array of any key-specific errors found. * @returns A `Promise` object. * * @example <caption>Example</caption> * * AsyncStorage.getAllKeys((err, keys) => { * AsyncStorage.multiGet(keys, (err, stores) => { * stores.map((result, i, store) => { * // get at each store's key/value so you can work with it * let key = store[i][0]; * let value = store[i][1]; * }); * }); * }); */ multiGet: function( keys: Array<string>, callback?: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void ): Promise { if (!this._immediate) { this._immediate = setImmediate(() => { this._immediate = null; this.flushGetRequests(); }); } var getRequest = { keys: keys, callback: callback, // do we need this? keyIndex: this._getKeys.length, resolve: null, reject: null, }; var promiseResult = new Promise((resolve, reject) => { getRequest.resolve = resolve; getRequest.reject = reject; }); this._getRequests.push(getRequest); // avoid fetching duplicates keys.forEach(key => { if (this._getKeys.indexOf(key) === -1) { this._getKeys.push(key); } }); return promiseResult; }, /** * Use this as a batch operation for storing multiple key-value pairs. When * the operation completes you'll get a single callback with any errors: * * ``` * multiSet([['k1', 'val1'], ['k2', 'val2']], cb); * ``` * * The method returns a `Promise` object. * * @param keyValuePairs Array of key-value array for the items to set. * @param callback Function that will be called with an array of any * key-specific errors found. * @returns A `Promise` object. * Example: see the `multiMerge` example. */ multiSet: function( keyValuePairs: Array<Array<string>>, callback?: ?(errors: ?Array<Error>) => void ): Promise { return new Promise((resolve, reject) => { RCTAsyncStorage.multiSet(keyValuePairs, function(errors) { var error = convertErrors(errors); callback && callback(error); if (error) { reject(error); } else { resolve(null); } }); }); }, /** * Call this to batch the deletion of all keys in the `keys` array. Returns * a `Promise` object. * * @param keys Array of key for the items to delete. * @param callback Function that will be called an array of any key-specific * errors found. * @returns A `Promise` object. * * @example <caption>Example</caption> * let keys = ['k1', 'k2']; * AsyncStorage.multiRemove(keys, (err) => { * // keys k1 & k2 removed, if they existed * // do most stuff after removal (if you want) * }); */ multiRemove: function( keys: Array<string>, callback?: ?(errors: ?Array<Error>) => void ): Promise { return new Promise((resolve, reject) => { RCTAsyncStorage.multiRemove(keys, function(errors) { var error = convertErrors(errors); callback && callback(error); if (error) { reject(error); } else { resolve(null); } }); }); }, /** * Batch operation to merge in existing and new values for a given set of * keys. This assumes that the values are stringified JSON. Returns a * `Promise` object. * * **NOTE**: This is not supported by all native implementations. * * @param keyValuePairs Array of key-value array for the items to merge. * @param callback Function that will be called with an array of any * key-specific errors found. * @returns A `Promise` object. * * @example <caption>Example</caption> * // first user, initial values * let UID234_object = { * name: 'Chris', * age: 30, * traits: {hair: 'brown', eyes: 'brown'}, * }; * * // first user, delta values * let UID234_delta = { * age: 31, * traits: {eyes: 'blue', shoe_size: 10}, * }; * * // second user, initial values * let UID345_object = { * name: 'Marge', * age: 25, * traits: {hair: 'blonde', eyes: 'blue'}, * }; * * // second user, delta values * let UID345_delta = { * age: 26, * traits: {eyes: 'green', shoe_size: 6}, * }; * * let multi_set_pairs = [['UID234', JSON.stringify(UID234_object)], ['UID345', JSON.stringify(UID345_object)]] * let multi_merge_pairs = [['UID234', JSON.stringify(UID234_delta)], ['UID345', JSON.stringify(UID345_delta)]] * * AsyncStorage.multiSet(multi_set_pairs, (err) => { * AsyncStorage.multiMerge(multi_merge_pairs, (err) => { * AsyncStorage.multiGet(['UID234','UID345'], (err, stores) => { * stores.map( (result, i, store) => { * let key = store[i][0]; * let val = store[i][1]; * console.log(key, val); * }); * }); * }); * }); * * // Console log results: * // => UID234 {"name":"Chris","age":31,"traits":{"shoe_size":10,"hair":"brown","eyes":"blue"}} * // => UID345 {"name":"Marge","age":26,"traits":{"shoe_size":6,"hair":"blonde","eyes":"green"}} */ multiMerge: function( keyValuePairs: Array<Array<string>>, callback?: ?(errors: ?Array<Error>) => void ): Promise { return new Promise((resolve, reject) => { RCTAsyncStorage.multiMerge(keyValuePairs, function(errors) { var error = convertErrors(errors); callback && callback(error); if (error) { reject(error); } else { resolve(null); } }); }); }, }; // Not all native implementations support merge. if (!RCTAsyncStorage.multiMerge) { delete AsyncStorage.mergeItem; delete AsyncStorage.multiMerge; } function convertErrors(errs) { if (!errs) { return null; } return (Array.isArray(errs) ? errs : [errs]).map((e) => convertError(e)); } function convertError(error) { if (!error) { return null; } var out = new Error(error.message); out.key = error.key; // flow doesn't like this :( return out; } module.exports = AsyncStorage;
nativeExample/reactRedux/__tests__/index.android.js
zhanglizhao/react-native-knowledge
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
src/pages/NotFoundPage.js
bshevchenko/ChronoMint
import React from 'react' const NotFoundPage = () => { return ( <div> <div> 404 Page Not Found </div> </div> ) } export default NotFoundPage
node_modules/material-ui/lib/svg-icons/action/perm-scan-wifi.js
DocWave/Doc-tor
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _svgIcon = require('../../svg-icon'); var _svgIcon2 = _interopRequireDefault(_svgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ActionPermScanWifi = _react2.default.createClass({ displayName: 'ActionPermScanWifi', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement( _svgIcon2.default, this.props, _react2.default.createElement('path', { d: 'M12 3C6.95 3 3.15 4.85 0 7.23L12 22 24 7.25C20.85 4.87 17.05 3 12 3zm1 13h-2v-6h2v6zm-2-8V6h2v2h-2z' }) ); } }); exports.default = ActionPermScanWifi; module.exports = exports['default'];
docs/pages/CustomComponents/AlternativeMedia/Icon.js
jossmac/react-images
// @flow // @jsx glam import glam from 'glam' import React from 'react' type IconProps = { size: number, type: 'play' | 'pause' } const Icon = ({ size = 64, type }: IconProps) => { const get = { play: ( <path d="M12 20.016c4.406 0 8.016-3.609 8.016-8.016s-3.609-8.016-8.016-8.016-8.016 3.609-8.016 8.016 3.609 8.016 8.016 8.016zM12 2.016c5.531 0 9.984 4.453 9.984 9.984s-4.453 9.984-9.984 9.984-9.984-4.453-9.984-9.984 4.453-9.984 9.984-9.984zM9.984 16.5v-9l6 4.5z" /> ), pause: ( <path d="M12.984 15.984v-7.969h2.016v7.969h-2.016zM12 20.016c4.406 0 8.016-3.609 8.016-8.016s-3.609-8.016-8.016-8.016-8.016 3.609-8.016 8.016 3.609 8.016 8.016 8.016zM12 2.016c5.531 0 9.984 4.453 9.984 9.984s-4.453 9.984-9.984 9.984-9.984-4.453-9.984-9.984 4.453-9.984 9.984-9.984zM9 15.984v-7.969h2.016v7.969h-2.016z" /> ), } return ( <svg role="presentation" viewBox="0 0 24 24" css={{ display: 'inline-block', fill: 'currentColor', height: size, stroke: 'currentColor', strokeWidth: 0, width: size, }} > {get[type]} </svg> ) } export default Icon
source/components/Texts/FullTextReveal.js
mikey1384/twin-kle
import React from 'react'; import PropTypes from 'prop-types'; import ErrorBoundary from 'components/Wrappers/ErrorBoundary'; import { Color } from 'constants/css'; FullTextReveal.propTypes = { direction: PropTypes.string, show: PropTypes.bool, style: PropTypes.object, text: PropTypes.string.isRequired }; export default function FullTextReveal({ direction = 'right', style, show, text }) { return ( <ErrorBoundary style={{ position: 'relative' }}> <div style={{ float: 'left', marginTop: 0, display: show ? 'block' : 'none', zIndex: 10, padding: '0.5rem', top: '100%', right: direction === 'right' ? 'auto' : 0, left: direction === 'left' ? 'auto' : 0, minWidth: '10rem', width: '100%', position: 'absolute', background: '#fff', boxShadow: `0 0 1px ${Color.black(0.9)}`, fontWeight: 'normal', lineHeight: 1.5, whiteSpace: 'pre-wrap', overflowWrap: 'break-word', ...style }} > {text} </div> </ErrorBoundary> ); }
src/svg-icons/action/list.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionList = (props) => ( <SvgIcon {...props}> <path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"/> </SvgIcon> ); ActionList = pure(ActionList); ActionList.displayName = 'ActionList'; ActionList.muiName = 'SvgIcon'; export default ActionList;
src/SwitchesToggleMenu/index.js
christianalfoni/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import styles from './styles.css'; class SwitchesToggleMenu extends React.Component { constructor(props) { super(props); this.options = this.props.options; this.optionCount = this.options.length; this.optionWidth = `${100 / this.optionCount}%`; this.checkedOption = this.props.checkedOption; } renderSwitches() { return (this.options.map((option, index) => { return ( <div className={this.props.checkedOption === index ? styles.optionActive : styles.optionInactive} key={index} onClick={() => { this.checkedOption = this.props.checkedOption; }} style={{ width: this.optionWidth }} >{option} </div> ); })); } render() { return ( <div className={styles.optionContainer}> {this.renderSwitches()} </div> ); } } SwitchesToggleMenu.displayName = 'SwitchesToggleMenu'; SwitchesToggleMenu.propTypes = { checkedOption: PropTypes.number, options: PropTypes.arrayOf(PropTypes.string) }; export default SwitchesToggleMenu;
client/main.js
hr-memories/greenfield
import Exponent from 'exponent'; import React from 'react'; import Login from './login'; import Homescreen from './homescreen'; import Memory from './memory'; import Memories from './memories'; import { Navigator } from 'react-native'; class App extends React.Component { renderScene(route, navigator) { if (route.name === 'Login') { return <Login navigator={navigator} />; } if (route.name === 'Homescreen') { return <Homescreen navigator={navigator} {...route.passProps}/>; } if (route.name === 'Memory') { return <Memory navigator={navigator} {...route.passProps}/>; } if (route.name === 'Memories') { return <Memories navigator={navigator} {...route.passProps}/>; } } render() { return ( <Navigator initialRoute={{ name: 'Login' }} renderScene={this.renderScene} /> ); } } Exponent.registerRootComponent(App);
ajax/libs/muicss/0.4.1/react/mui-react.min.js
BenjaminVanRyseghem/cdnjs
!function(e){var t=e.babelHelpers={};t["typeof"]="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},t.jsx=function(){var e="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;return function(t,r,n,l){var o=t&&t.defaultProps,s=arguments.length-3;if(r||0===s||(r={}),r&&o)for(var a in o)void 0===r[a]&&(r[a]=o[a]);else r||(r=o||{});if(1===s)r.children=l;else if(s>1){for(var i=Array(s),u=0;s>u;u++)i[u]=arguments[u+3];r.children=i}return{$$typeof:e,type:t,key:void 0===n?null:""+n,ref:null,props:r,_owner:null}}}(),t.asyncToGenerator=function(e){return function(){var t=e.apply(this,arguments);return new Promise(function(e,r){function n(l,o){try{var s=t[l](o),a=s.value}catch(i){return void r(i)}return s.done?void e(a):Promise.resolve(a).then(function(e){return n("next",e)},function(e){return n("throw",e)})}return n("next")})}},t.classCallCheck=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},t.createClass=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.defineEnumerableProperties=function(e,t){for(var r in t){var n=t[r];n.configurable=n.enumerable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,r,n)}return e},t.defaults=function(e,t){for(var r=Object.getOwnPropertyNames(t),n=0;n<r.length;n++){var l=r[n],o=Object.getOwnPropertyDescriptor(t,l);o&&o.configurable&&void 0===e[l]&&Object.defineProperty(e,l,o)}return e},t.defineProperty=function(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},t["extends"]=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},t.get=function r(e,t,n){null===e&&(e=Function.prototype);var l=Object.getOwnPropertyDescriptor(e,t);if(void 0===l){var o=Object.getPrototypeOf(e);return null===o?void 0:r(o,t,n)}if("value"in l)return l.value;var s=l.get;if(void 0!==s)return s.call(n)},t.inherits=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},t["instanceof"]=function(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?t[Symbol.hasInstance](e):e instanceof t},t.interopRequireDefault=function(e){return e&&e.__esModule?e:{"default":e}},t.interopRequireWildcard=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t["default"]=e,t},t.newArrowCheck=function(e,t){if(e!==t)throw new TypeError("Cannot instantiate an arrow function")},t.objectDestructuringEmpty=function(e){if(null==e)throw new TypeError("Cannot destructure undefined")},t.objectWithoutProperties=function(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},t.possibleConstructorReturn=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},t.selfGlobal="undefined"==typeof e?self:e,t.set=function n(e,t,r,l){var o=Object.getOwnPropertyDescriptor(e,t);if(void 0===o){var s=Object.getPrototypeOf(e);null!==s&&n(s,t,r,l)}else if("value"in o&&o.writable)o.value=r;else{var a=o.set;void 0!==a&&a.call(l,r)}return r},t.slicedToArray=function(){function e(e,t){var r=[],n=!0,l=!1,o=void 0;try{for(var s,a=e[Symbol.iterator]();!(n=(s=a.next()).done)&&(r.push(s.value),!t||r.length!==t);n=!0);}catch(i){l=!0,o=i}finally{try{!n&&a["return"]&&a["return"]()}finally{if(l)throw o}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),t.slicedToArrayLoose=function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e)){for(var r,n=[],l=e[Symbol.iterator]();!(r=l.next()).done&&(n.push(r.value),!t||n.length!==t););return n}throw new TypeError("Invalid attempt to destructure non-iterable instance")},t.taggedTemplateLiteral=function(e,t){return Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))},t.taggedTemplateLiteralLoose=function(e,t){return e.raw=t,e},t.temporalRef=function(e,t,r){if(e===r)throw new ReferenceError(t+" is not defined - temporal dead zone");return e},t.temporalUndefined={},t.toArray=function(e){return Array.isArray(e)?e:Array.from(e)},t.toConsumableArray=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}}("undefined"==typeof global?self:global),function e(t,r,n){function l(s,a){if(!r[s]){if(!t[s]){var i="function"==typeof require&&require;if(!a&&i)return i(s,!0);if(o)return o(s,!0);throw new Error("Cannot find module '"+s+"'")}var u=r[s]={exports:{}};t[s][0].call(u.exports,function(e){var r=t[s][1][e];return l(r?r:e)},u,u.exports,e,t,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s<n.length;s++)l(n[s]);return l}({1:[function(e,t,r){"use strict";!function(t){if(!t._muiReactLoaded){t._muiReactLoaded=!0;var r=t.mui=t.mui||[],n=r.react={};n.Appbar=e("src/react/appbar"),n.Button=e("src/react/button"),n.Caret=e("src/react/caret"),n.Checkbox=e("src/react/checkbox"),n.Col=e("src/react/col"),n.Container=e("src/react/container"),n.Divider=e("src/react/divider"),n.Dropdown=e("src/react/dropdown"),n.DropdownItem=e("src/react/dropdown-item"),n.Form=e("src/react/form"),n.Panel=e("src/react/panel"),n.Radio=e("src/react/radio"),n.Row=e("src/react/row"),n.Select=e("src/react/select"),n.SelectItem=e("src/react/select-item"),n.Tab=e("src/react/tab"),n.Tabs=e("src/react/tabs"),n.TextInput=e("src/react/text-input"),n.TextareaInput=e("src/react/textarea-input")}}(window)},{"src/react/appbar":10,"src/react/button":11,"src/react/caret":12,"src/react/checkbox":13,"src/react/col":14,"src/react/container":15,"src/react/divider":16,"src/react/dropdown":18,"src/react/dropdown-item":17,"src/react/form":19,"src/react/panel":20,"src/react/radio":21,"src/react/row":22,"src/react/select":24,"src/react/select-item":23,"src/react/tab":25,"src/react/tabs":26,"src/react/text-input":27,"src/react/textarea-input":28}],2:[function(e,t,r){"use strict";t.exports={debug:!0}},{}],3:[function(e,t,r){"use strict";function n(e,t,r){var n,i,u,c,p=document.documentElement.clientHeight,d=t*s+2*a,f=Math.min(d,p);i=a+s-(l+o),i-=r*s,u=-1*e.getBoundingClientRect().top,c=p-f+u,n=Math.min(Math.max(i,u),c);var b,h,v=0;return d>p&&(b=a+(r+1)*s-(-1*n+l+o),h=t*s+2*a-f,v=Math.min(b,h)),{height:f+"px",top:n+"px",scrollTop:v}}var l=15,o=32,s=42,a=8;t.exports={getMenuPositionalCSS:n}},{}],4:[function(e,t,r){"use strict";function n(e,t){if(t&&e.setAttribute){for(var r,n=h(e),l=t.split(" "),o=0;o<l.length;o++)r=l[o].trim(),-1===n.indexOf(" "+r+" ")&&(n+=r+" ");e.setAttribute("class",n.trim())}}function l(e,t,r){if(void 0===t)return getComputedStyle(e);var n=s(t);{if("object"!==n){"string"===n&&void 0!==r&&(e.style[v(t)]=r);var l=getComputedStyle(e),o="array"===s(t);if(!o)return y(e,t,l);for(var a,i={},u=0;u<t.length;u++)a=t[u],i[a]=y(e,a,l);return i}for(var a in t)e.style[v(a)]=t[a]}}function o(e,t){return t&&e.getAttribute?h(e).indexOf(" "+t+" ")>-1:!1}function s(e){if(void 0===e)return"undefined";var t=Object.prototype.toString.call(e);if(0===t.indexOf("[object "))return t.slice(8,-1).toLowerCase();throw new Error("MUI: Could not understand type: "+t)}function a(e,t,r,n){n=void 0===n?!1:n,e.addEventListener(t,r,n);var l=e._muiEventCache=e._muiEventCache||{};l[t]=l[t]||[],l[t].push([r,n])}function i(e,t,r,n){n=void 0===n?!1:n;var l,o,s=e._muiEventCache=e._muiEventCache||{},a=s[t]||[];for(o=a.length;o--;)l=a[o],(void 0===r||l[0]===r&&l[1]===n)&&(a.splice(o,1),e.removeEventListener(t,l[0],l[1]))}function u(e,t,r,n){a(e,t,function l(n){r&&r.apply(this,arguments),i(e,t,l)},n)}function c(e,t){var r=window;if(void 0===t){if(e===r){var n=document.documentElement;return(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}return e.scrollLeft}e===r?r.scrollTo(t,p(r)):e.scrollLeft=t}function p(e,t){var r=window;if(void 0===t){if(e===r){var n=document.documentElement;return(r.pageYOffset||n.scrollTop)-(n.clientTop||0)}return e.scrollTop}e===r?r.scrollTo(c(r),t):e.scrollTop=t}function d(e){var t=window,r=e.getBoundingClientRect(),n=p(t),l=c(t);return{top:r.top+n,left:r.left+l,height:r.height,width:r.width}}function f(e){var t=!1,r=!0,n=document,l=n.defaultView,o=n.documentElement,s=n.addEventListener?"addEventListener":"attachEvent",a=n.addEventListener?"removeEventListener":"detachEvent",i=n.addEventListener?"":"on",u=function d(r){("readystatechange"!=r.type||"complete"==n.readyState)&&(("load"==r.type?l:n)[a](i+r.type,d,!1),!t&&(t=!0)&&e.call(l,r.type||r))},c=function f(){try{o.doScroll("left")}catch(e){return void setTimeout(f,50)}u("poll")};if("complete"==n.readyState)e.call(l,"lazy");else{if(n.createEventObject&&o.doScroll){try{r=!l.frameElement}catch(p){}r&&c()}n[s](i+"DOMContentLoaded",u,!1),n[s](i+"readystatechange",u,!1),l[s](i+"load",u,!1)}}function b(e,t){if(t&&e.setAttribute){for(var r,n=h(e),l=t.split(" "),o=0;o<l.length;o++)for(r=l[o].trim();n.indexOf(" "+r+" ")>=0;)n=n.replace(" "+r+" "," ");e.setAttribute("class",n.trim())}}function h(e){var t=(e.getAttribute("class")||"").replace(/[\n\t]/g,"");return" "+t+" "}function v(e){return e.replace(C,function(e,t,r,n){return n?r.toUpperCase():r}).replace(g,"Moz$1")}function y(e,t,r){var n;return n=r.getPropertyValue(t),""!==n||e.ownerDocument||(n=e.style[v(t)]),n}var m,C=/([\:\-\_]+(.))/g,g=/^moz([A-Z])/;m={multiple:!0,selected:!0,checked:!0,disabled:!0,readonly:!0,required:!0,open:!0},t.exports={addClass:n,css:l,hasClass:o,off:i,offset:d,on:a,one:u,ready:f,removeClass:b,type:s,scrollLeft:c,scrollTop:p}},{}],5:[function(e,t,r){"use strict";function n(){var e=window;if(v.debug&&"undefined"!=typeof e.console)try{e.console.log.apply(e.console,arguments)}catch(t){var r=Array.prototype.slice.call(arguments);e.console.log(r.join("\n"))}}function l(e){var t,r=document;t=r.head||r.getElementsByTagName("head")[0]||r.documentElement;var n=r.createElement("style");return n.type="text/css",n.styleSheet?n.styleSheet.cssText=e:n.appendChild(r.createTextNode(e)),t.insertBefore(n,t.firstChild),n}function o(e,t){if(!t)throw new Error("MUI: "+e);"undefined"!=typeof console&&console.error("MUI Warning: "+e)}function s(e){if(m.push(e),void 0===m._initialized){var t=document;y.on(t,"animationstart",a),y.on(t,"mozAnimationStart",a),y.on(t,"webkitAnimationStart",a),m._initialized=!0}}function a(e){if("mui-node-inserted"===e.animationName)for(var t=e.target,r=m.length-1;r>=0;r--)m[r](t)}function i(e){var t="";for(var r in e)t+=e[r]?r+" ":"";return t.trim()}function u(){if(void 0!==h)return h;var e=document.createElement("x");return e.style.cssText="pointer-events:auto",h="auto"===e.style.pointerEvents}function c(e,t){return function(){e[t].apply(e,arguments)}}function p(e,t,r,n,l){var o,s=document.createEvent("HTMLEvents"),r=void 0!==r?r:!0,n=void 0!==n?n:!0;if(s.initEvent(t,r,n),l)for(o in l)s[o]=l[o];return e&&e.dispatchEvent(s),s}function d(){if(C+=1,1===C){var e=window,t=document;b={left:y.scrollLeft(e),top:y.scrollTop(e)},y.addClass(t.body,g),e.scrollTo(b.left,b.top)}}function f(){if(0!==C&&(C-=1,0===C)){var e=window,t=document;y.removeClass(t.body,g),e.scrollTo(b.left,b.top)}}var b,h,v=e("../config"),y=e("./jqLite"),m=[],C=0,g="mui-body--scroll-lock";t.exports={callback:c,classNames:i,disableScrollLock:f,dispatchEvent:p,enableScrollLock:d,log:n,loadStyle:l,onNodeInserted:s,raiseError:o,supportsPointerEvents:u}},{"../config":2,"./jqLite":4}],6:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.TextField=void 0;var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=babelHelpers.interopRequireWildcard(o),a=l["default"].PropTypes,i=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e)),n=e.value,l=n||e.defaultValue;if(r.state={innerValue:l,isDirty:Boolean(l)},null!==n&&null===e.onChange){var o="You provided a `value` prop to a form field without an `OnChange` handler. Please see React documentation on controlled components";s.raiseError(o,!0)}var a=s.callback;return r.onChangeCB=a(r,"onChange"),r.onFocusCB=a(r,"onFocus"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){this.refs.inputEl._muiTextfield=!0}},{key:"onChange",value:function(e){this.setState({innerValue:e.target.value}),this.props.onChange&&this.props.onChange(e)}},{key:"onFocus",value:function(e){this.setState({isDirty:!0})}},{key:"triggerFocus",value:function(){this.refs.inputEl.focus()}},{key:"render",value:function(){var e={},t=Boolean(this.state.innerValue),r=void 0;return e["mui--is-empty"]=!t,e["mui--is-not-empty"]=t,e["mui--is-dirty"]=this.state.isDirty,e["mui--is-invalid"]=this.props.invalid,e=s.classNames(e),r="textarea"===this.props.type?l["default"].createElement("textarea",{ref:"inputEl",className:e,rows:this.props.rows,placeholder:this.props.hint,value:this.props.value,defaultValue:this.props.defaultValue,autoFocus:this.props.autoFocus,onChange:this.onChangeCB,onFocus:this.onFocusCB,required:this.props.required}):l["default"].createElement("input",{ref:"inputEl",className:e,type:this.props.type,value:this.props.value,defaultValue:this.props.defaultValue,placeholder:this.props.hint,autoFocus:this.props.autofocus,onChange:this.onChangeCB,onFocus:this.onFocusCB,required:this.props.required})}}]),t}(l["default"].Component);i.propTypes={hint:a.string,value:a.string,type:a.string,autoFocus:a.bool,onChange:a.func},i.defaultProps={hint:null,type:null,value:null,autoFocus:!1,onChange:null};var u=function(e){function t(){var e,r,n,l;babelHelpers.classCallCheck(this,t);for(var o=arguments.length,s=Array(o),a=0;o>a;a++)s[a]=arguments[a];return r=n=babelHelpers.possibleConstructorReturn(this,(e=Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.state={style:{}},l=r,babelHelpers.possibleConstructorReturn(n,l)}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){var e=this;setTimeout(function(){var t=".15s ease-out",r=void 0;r={transition:t,WebkitTransition:t,MozTransition:t,OTransition:t,msTransform:t},e.setState({style:r})},150)}},{key:"render",value:function(){return l["default"].createElement("label",{style:this.state.style,onClick:this.props.onClick},this.props.text)}}]),t}(l["default"].Component);u.defaultProps={text:"",onClick:null};var c=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));return r.onClickCB=s.callback(r,"onClick"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"onClick",value:function(e){s.supportsPointerEvents()===!1&&(e.target.style.cursor="text",this.refs.inputEl.triggerFocus())}},{key:"render",value:function(){var e={},t=void 0;return this.props.label.length&&(t=l["default"].createElement(u,{text:this.props.label,onClick:this.onClickCB})),e["mui-textfield"]=!0,e["mui-textfield--float-label"]=this.props.floatingLabel,e=s.classNames(e),l["default"].createElement("div",{className:e},l["default"].createElement(i,babelHelpers["extends"]({ref:"inputEl"},this.props)),t)}}]),t}(l["default"].Component);c.propTypes={label:a.string,floatingLabel:a.bool},c.defaultProps={label:"",floatingLabel:!1},r.TextField=c},{"../js/lib/util":5,react:"CwoHg3"}],7:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/jqLite"),s=babelHelpers.interopRequireWildcard(o),a=e("../js/lib/util"),i=(babelHelpers.interopRequireWildcard(a),l["default"].PropTypes),u="mui-btn",c="mui-ripple-effect",p={color:1,variant:1,size:1},d=function(e){function t(){var e,r,n,l;babelHelpers.classCallCheck(this,t);for(var o=arguments.length,s=Array(o),a=0;o>a;a++)s[a]=arguments[a];return r=n=babelHelpers.possibleConstructorReturn(this,(e=Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.state={ripples:{}},l=r,babelHelpers.possibleConstructorReturn(n,l)}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){var e=this.refs.buttonEl;e._muiDropdown=!0,e._muiRipple=!0}},{key:"onClick",value:function(e){var t=this.props.onClick;t&&t(e)}},{key:"onMouseDown",value:function(e){var t=s.offset(this.refs.buttonEl),r=t.height;"fab"===this.props.variant&&(r/=2);var n=this.state.ripples,l=Date.now();n[l]={xPos:e.pageX-t.left,yPos:e.pageY-t.top,diameter:r,teardownFn:this.teardownRipple.bind(this,l)},this.setState({ripples:n})}},{key:"onTouchStart",value:function(e){}},{key:"teardownRipple",value:function(e){var t=this.state.ripples;delete t[e],this.setState({ripples:t})}},{key:"render",value:function(){var e=u,t=void 0,r=void 0,n=this.state.ripples;for(t in p)r=this.props[t],"default"!==r&&(e+=" "+u+"--"+r);return l["default"].createElement("button",{ref:"buttonEl",type:this.props.type,className:e+" "+this.props.className,disabled:this.props.disabled,onClick:this.onClick.bind(this),onMouseDown:this.onMouseDown.bind(this),style:this.props.style},this.props.children,Object.keys(n).map(function(e,t){var r=n[e];return l["default"].createElement(f,{key:e,xPos:r.xPos,yPos:r.yPos,diameter:r.diameter,onTeardown:r.teardownFn})}))}}]),t}(l["default"].Component);d.propTypes={color:i.oneOf(["default","primary","danger","dark","accent"]),disabled:i.bool,size:i.oneOf(["default","small","large"]),type:i.oneOf(["submit","button"]),variant:i.oneOf(["default","flat","raised","fab"]),onClick:i.func},d.defaultProps={className:"",color:"default",disabled:!1,size:"default",type:null,variant:"default",onClick:null};var f=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){var e=this,t=setTimeout(function(){var t=e.props.onTeardown;t&&t()},2e3);this.setState({teardownTimer:t})}},{key:"componentWillUnmount",value:function(){clearTimeout(this.state.teardownTimer)}},{key:"render",value:function(){var e=this.props.diameter,t=e/2,r={height:e,width:e,top:this.props.yPos-t||0,left:this.props.xPos-t||0};return l["default"].createElement("div",{className:c,style:r})}}]),t}(l["default"].Component);f.propTypes={xPos:i.number,yPos:i.number,diameter:i.number,onTeardown:i.func},f.defaultProps={xPos:0,yPos:0,diameter:0,onTeardown:null},r["default"]=d,t.exports=r["default"]},{"../js/lib/jqLite":4,"../js/lib/util":5,react:"CwoHg3"}],8:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("span",{className:"mui-caret "+this.props.className,style:this.props.style})}}]),t}(l["default"].Component);o.defaultProps={className:""},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],9:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=l["default"].PropTypes,s=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return null}}]),t}(l["default"].Component);s.propTypes={value:o.any,label:o.string,onActive:o.func},s.defaultProps={value:null,label:"",onActive:null},r["default"]=s,t.exports=r["default"]},{react:"CwoHg3"}],10:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("div",{className:"mui-appbar "+this.props.className,style:this.props.style},this.props.children)}}]),t}(l["default"].Component);o.defaultProps={className:""},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],11:[function(e,t,r){t.exports=e(7)},{"../js/lib/jqLite":4,"../js/lib/util":5,react:"CwoHg3"}],12:[function(e,t,r){t.exports=e(8)},{react:"CwoHg3"}],13:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=l["default"].PropTypes,s=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("div",{className:"mui-checkbox "+this.props.className,style:this.props.style},l["default"].createElement("label",null,l["default"].createElement("input",{type:"checkbox",value:this.props.value,checked:this.props.checked,defaultChecked:this.props.defaultChecked,disabled:this.props.disabled}),this.props.label))}}]),t}(l["default"].Component);s.propTypes={label:o.string,value:o.string,checked:o.bool,defaultChecked:o.bool,disabled:o.bool},s.defaultProps={className:"",label:null,value:null,checked:null,defaultChecked:null,disabled:!1},r["default"]=s,t.exports=r["default"]},{react:"CwoHg3"}],14:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=babelHelpers.interopRequireWildcard(o),a=["xs","sm","md","lg","xl"],i=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"defaultProps",value:function(){var e={className:""},t=void 0,r=void 0;for(t=a.length-1;t>-1;t--)r=a[t],e[r]=null,e[r+"-offset"]=null;return e}},{key:"render",value:function(){var e={},t=void 0,r=void 0,n=void 0,o=void 0;for(t=a.length-1;t>-1;t--)r=a[t],o="mui-col-"+r,n=this.props[r],n&&(e[o+"-"+n]=!0),n=this.props[r+"-offset"],n&&(e[o+"-offset-"+n]=!0);return e=s.classNames(e),l["default"].createElement("div",{className:e+" "+this.props.className,style:this.props.style},this.props.children)}}]),t}(l["default"].Component);r["default"]=i,t.exports=r["default"]},{"../js/lib/util":5,react:"CwoHg3"}],15:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e="mui-container";return this.props.fluid&&(e+="-fluid"),l["default"].createElement("div",{className:e+" "+this.props.className,style:this.props.style},this.props.children)}}]),t}(l["default"].Component);o.propTypes={fluid:l["default"].PropTypes.bool},o.defaultProps={className:"",fluid:!1},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],16:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("div",{className:"mui-divider "+this.props.className,style:this.props.style})}}]),t}(l["default"].Component);o.defaultProps={className:""},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],17:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=babelHelpers.interopRequireWildcard(o),a=l["default"].PropTypes,i=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));return r.onClickCB=s.callback(r,"onClick"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"onClick",value:function(e){this.props.onClick&&this.props.onClick(this,e)}},{key:"render",value:function(){return l["default"].createElement("li",null,l["default"].createElement("a",{href:this.props.link,onClick:this.onClickCB},this.props.children))}}]),t}(l["default"].Component);i.propTypes={link:a.string,onClick:a.func},i.defaultProps={link:null,onClick:null},r["default"]=i,t.exports=r["default"]},{"../js/lib/util":5,react:"CwoHg3"}],18:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("./button"),s=babelHelpers.interopRequireDefault(o),a=e("./caret"),i=babelHelpers.interopRequireDefault(a),u=e("../js/lib/jqLite"),c=(babelHelpers.interopRequireWildcard(u),e("../js/lib/util")),p=babelHelpers.interopRequireWildcard(c),d=l["default"].PropTypes,f="mui-dropdown",b="mui-dropdown__menu",h="mui--is-open",v="mui-dropdown__menu--right",y=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));r.state={opened:!1,menuTop:0};var n=p.callback;return r.onClickCB=n(r,"onClick"),r.onOutsideClickCB=n(r,"onOutsideClick"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentWillMount",value:function(){document.addEventListener("click",this.onOutsideClickCB)}},{key:"componentWillUnmount",value:function(){document.removeEventListener("click",this.onOutsideClickCB)}},{key:"onClick",value:function(e){0===e.button&&(this.props.disabled||e.defaultPrevented||this.toggle())}},{key:"toggle",value:function(){return this.props.children?void(this.state.opened?this.close():this.open()):p.raiseError("Dropdown menu element not found")}},{key:"open",value:function(){var e=this.refs.wrapperEl.getBoundingClientRect(),t=void 0;t=this.refs.button.refs.buttonEl.getBoundingClientRect(),this.setState({opened:!0,menuTop:t.top-e.top+t.height})}},{key:"close",value:function(){this.setState({opened:!1})}},{key:"select",value:function(){this.props.onClick&&this.props.onClick(this,ev)}},{key:"onOutsideClick",value:function(e){var t=this.refs.wrapperEl.contains(e.target);t||this.close()}},{key:"render",value:function(){var e=void 0,t=void 0;if(e=l["default"].createElement(s["default"],{ref:"button",type:"button",onClick:this.onClickCB,color:this.props.color,variant:this.props.variant,size:this.props.size,disabled:this.props.disabled},this.props.label,l["default"].createElement(i["default"],null)),this.state.opened){var r={};r[b]=!0,r[h]=this.state.opened,r[v]="right"===this.props.alignMenu,r=p.classNames(r),t=l["default"].createElement("ul",{ref:"menuEl",className:r,style:{top:this.state.menuTop},onClick:this.selectCB},this.props.children)}return l["default"].createElement("div",{ref:"wrapperEl",className:f+" "+this.props.className,style:this.props.style},e,t)}}]),t}(l["default"].Component);y.propTypes={color:d.oneOf(["default","primary","danger","dark","accent"]),variant:d.oneOf(["default","flat","raised","fab"]),size:d.oneOf(["default","small","large"]),label:d.string,alignMenu:d.oneOf(["left","right"]),onClick:d.func,disabled:d.bool},y.defaultProps={className:"",color:"default",variant:"default",size:"default",label:"",alignMenu:"left",onClick:null,disabled:!1},r["default"]=y,t.exports=r["default"]},{"../js/lib/jqLite":4,"../js/lib/util":5,"./button":7,"./caret":8,react:"CwoHg3"}],19:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){var e="";return this.props.inline&&(e="mui-form--inline"),l["default"].createElement("form",{className:e+" "+this.props.className,style:this.props.style},this.props.children)}}]),t}(l["default"].Component);o.propTypes={inline:l["default"].PropTypes.bool},o.defaultProps={className:"",inline:!1},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],20:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("div",{className:"mui-panel "+this.props.className,style:this.props.style},this.props.children)}}]),t}(l["default"].Component);o.defaultProps={className:""},r["default"]=o,t.exports=r["default"]},{react:"CwoHg3"}],21:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=l["default"].PropTypes,s=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("div",{className:"mui-radio "+this.props.className,style:this.props.style},l["default"].createElement("label",null,l["default"].createElement("input",{type:"radio",name:this.props.name,value:this.props.value,checked:this.props.checked,defaultChecked:this.props.defaultChecked,disabled:this.props.disabled}),this.props.label))}}]),t}(l["default"].Component);s.propTypes={name:o.string,label:o.string,value:o.string,checked:o.bool,defaultChecked:o.bool,disabled:o.bool},s.defaultProps={className:"",name:null,label:null,value:null,checked:null,defaultChecked:null,disabled:!1},r["default"]=s,t.exports=r["default"]},{react:"CwoHg3"}],22:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/util"),s=(babelHelpers.interopRequireWildcard(o),function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("div",{className:"mui-row "+this.props.className,style:this.props.style},this.props.children)}}]),t}(l["default"].Component));s.defaultProps={className:""},r["default"]=s,t.exports=r["default"]},{"../js/lib/util":5,react:"CwoHg3"}],23:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/forms"),s=(babelHelpers.interopRequireWildcard(o), e("../js/lib/jqLite")),a=(babelHelpers.interopRequireWildcard(s),e("../js/lib/util")),i=(babelHelpers.interopRequireWildcard(a),l["default"].PropTypes),u=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement("option",{value:this.props.value},this.props.label)}}]),t}(l["default"].Component);u.propTypes={value:i.string,label:i.string},u.defaultProps={value:null,label:null},r["default"]=u,t.exports=r["default"]},{"../js/lib/forms":3,"../js/lib/jqLite":4,"../js/lib/util":5,react:"CwoHg3"}],24:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("../js/lib/forms"),s=babelHelpers.interopRequireWildcard(o),a=e("../js/lib/jqLite"),i=babelHelpers.interopRequireWildcard(a),u=e("../js/lib/util"),c=babelHelpers.interopRequireWildcard(u),p=l["default"].PropTypes,d=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));r.state={readOnly:!1,showMenu:!1,value:null},r.state.readOnly=e.readOnly,r.state.value=e.value;var n=c.callback;return r.hideMenuCB=n(r,"hideMenu"),r.onInnerClickCB=n(r,"onInnerClick"),r.onInnerFocusCB=n(r,"onInnerFocus"),r.onInnerMouseDownCB=n(r,"onInnerMouseDown"),r.onKeydownCB=n(r,"onKeydown"),r.onMenuChangeCB=n(r,"onMenuChange"),r.onOuterFocusCB=n(r,"onOuterFocus"),r.onOuterBlurCB=n(r,"onOuterBlur"),e.onChange?r.onInnerChangeCB=n(r,"onInnerChange"):r.state.readOnly=!0,r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentDidMount",value:function(){this.refs.selectEl._muiSelect=!0,this.refs.wrapperEl.tabIndex=-1,this.props.autoFocus&&this.refs.wrapperEl.focus()}},{key:"onInnerMouseDown",value:function(e){0===e.button&&this.props.useDefault!==!0&&e.preventDefault()}},{key:"onInnerChange",value:function(e){if(!this.state.readOnly){var t=e.target.value;this.setState({value:t});var r=this.props.onChange;r&&r(t)}}},{key:"onInnerClick",value:function(e){0===e.button&&this.showMenu()}},{key:"onInnerFocus",value:function(e){var t=this;this.props.useDefault!==!0&&setTimeout(function(){t.refs.wrapperEl.focus()},0)}},{key:"onOuterFocus",value:function(e){if(e.target===this.refs.wrapperEl){var t=this.refs.selectEl;return t._muiOrigIndex=t.tabIndex,t.tabIndex=-1,t.disabled?this.refs.wrapperEl.blur():void i.on(document,"keydown",this.onKeydownCB)}}},{key:"onOuterBlur",value:function(e){if(e.target===this.refs.wrapperEl){var t=this.refs.selectEl;t.tabIndex=t._muiOrigIndex,i.off(document,"keydown",this.onKeydownCB)}}},{key:"onKeydown",value:function(e){(32===e.keyCode||38===e.keyCode||40===e.keyCode)&&(e.preventDefault(),this.refs.selectEl.disabled!==!0&&this.showMenu())}},{key:"showMenu",value:function(){this.props.useDefault!==!0&&(c.enableScrollLock(),i.on(window,"resize",this.hideMenuCB),i.on(document,"click",this.hideMenuCB),this.setState({showMenu:!0}))}},{key:"hideMenu",value:function(){c.disableScrollLock(),i.off(window,"resize",this.hideMenuCB),i.off(document,"click",this.hideMenuCB),this.setState({showMenu:!1}),this.refs.selectEl.focus()}},{key:"onMenuChange",value:function(e){if(!this.state.readOnly){this.setState({value:e});var t=this.props.onChange;t&&t(e)}}},{key:"render",value:function(){var e=void 0;return this.state.showMenu&&(e=l["default"].createElement(f,{optionEls:this.refs.selectEl.children,wrapperEl:this.refs.wrapperEl,onChange:this.onMenuChangeCB,onClose:this.hideMenuCB})),l["default"].createElement("div",{ref:"wrapperEl",className:"mui-select "+this.props.className,style:this.props.style,onFocus:this.onOuterFocusCB,onBlur:this.onOuterBlurCB},l["default"].createElement("select",{ref:"selectEl",name:this.props.name,value:this.state.value,defaultValue:this.props.defaultValue,disabled:this.props.disabled,multiple:this.props.multiple,readOnly:this.props.readOnly,required:this.props.required,onChange:this.onInnerChangeCB,onMouseDown:this.onInnerMouseDownCB,onClick:this.onInnerClickCB,onFocus:this.onInnerFocusCB},this.props.children),e)}}]),t}(l["default"].Component);d.propTypes={name:p.string,value:p.string,defaultValue:p.string,autoFocus:p.bool,disabled:p.bool,multiple:p.bool,readOnly:p.bool,required:p.bool,useDefault:p.bool,onChange:p.func},d.defaultProps={className:"",name:null,value:null,defaultValue:null,autoFocus:!1,disabled:!1,multiple:!1,readOnly:!1,required:!1,useDefault:!1,onChange:null};var f=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));return r.state={origIndex:null,currentIndex:null},r.onKeydownCB=c.callback(r,"onKeydown"),r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"componentWillMount",value:function(){var e=this.props.optionEls,t=e.length,r=0,n=void 0;for(n=t-1;n>-1;n--)e[n].selected&&(r=n);this.setState({origIndex:r,currentIndex:r})}},{key:"componentDidMount",value:function(){setTimeout(function(){var e=document.activeElement;"body"!==e.nodeName.toLowerCase()&&e.blur()},0);var e=s.getMenuPositionalCSS(this.props.wrapperEl,this.props.optionEls.length,this.state.currentIndex),t=this.refs.wrapperEl;i.css(t,e),i.scrollTop(t,e.scrollTop),i.on(document,"keydown",this.onKeydownCB)}},{key:"componentWillUnmount",value:function(){i.off(document,"keydown",this.onKeydownCB)}},{key:"onClick",value:function(e,t){t.stopPropagation(),this.selectAndDestroy(e)}},{key:"onKeydown",value:function(e){var t=e.keyCode;return 9===t?this.destroy():((27===t||40===t||38===t||13===t)&&e.preventDefault(),void(27===t?this.destroy():40===t?this.increment():38===t?this.decrement():13===t&&this.selectAndDestroy()))}},{key:"increment",value:function(){this.state.currentIndex!==this.props.optionEls.length-1&&this.setState({currentIndex:this.state.currentIndex+1})}},{key:"decrement",value:function(){0!==this.state.currentIndex&&this.setState({currentIndex:this.state.currentIndex-1})}},{key:"selectAndDestroy",value:function(e){e=void 0===e?this.state.currentIndex:e,e!==this.state.origIndex&&this.props.onChange(this.props.optionEls[e].value),this.destroy()}},{key:"destroy",value:function(){this.props.onClose()}},{key:"render",value:function(){var e=[],t=this.props.optionEls,r=t.length,n=void 0,o=void 0;for(o=0;r>o;o++)n=o===this.state.currentIndex?"mui--is-selected":"",e.push(l["default"].createElement("div",{key:o,className:n,onClick:this.onClick.bind(this,o)},t[o].textContent));return l["default"].createElement("div",{ref:"wrapperEl",className:"mui-select__menu"},e)}}]),t}(l["default"].Component);f.defaultProps={optionEls:[],wrapperEl:null,onChange:null,onClose:null},r["default"]=d,t.exports=r["default"]},{"../js/lib/forms":3,"../js/lib/jqLite":4,"../js/lib/util":5,react:"CwoHg3"}],25:[function(e,t,r){t.exports=e(9)},{react:"CwoHg3"}],26:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("./tab"),s=babelHelpers.interopRequireDefault(o),a=e("../js/lib/util"),i=babelHelpers.interopRequireWildcard(a),u=l["default"].PropTypes,c="mui-tabs__bar",p="mui-tabs__bar--justified",d="mui-tabs__pane",f="mui--is-active",b=function(e){function t(e){babelHelpers.classCallCheck(this,t);var r=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).call(this,e));return r.state={currentSelectedIndex:e.initialSelectedIndex},r}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"onClick",value:function(e,t,r){e!==this.state.currentSelectedIndex&&(this.setState({currentSelectedIndex:e}),t.props.onActive&&t.props.onActive(t),this.props.onChange&&this.props.onChange(e,t.props.value,t,r))}},{key:"render",value:function(){var e=[],t=[],r=this.props.children,n=r.length,o=this.state.currentSelectedIndex%n,a=void 0,u=void 0,b=void 0,h=void 0;for(h=0;n>h;h++)u=r[h],u.type!==s["default"]&&i.raiseError("Expecting MUITab React Element"),a=h===o?!0:!1,e.push(l["default"].createElement("li",{key:h,className:a?f:""},l["default"].createElement("a",{onClick:this.onClick.bind(this,h,u)},u.props.label))),b=d+" ",a&&(b+=f),t.push(l["default"].createElement("div",{key:h,className:b},u.props.children));return b=c,this.props.justified&&(b+=" "+p),l["default"].createElement("div",{className:this.props.className,style:this.props.style},l["default"].createElement("ul",{className:b},e),t)}}]),t}(l["default"].Component);b.propTypes={initialSelectedIndex:u.number,justified:u.bool,onChange:u.func},b.defaultProps={className:"",initialSelectedIndex:0,justified:!1,onChange:null},r["default"]=b,t.exports=r["default"]},{"../js/lib/util":5,"./tab":9,react:"CwoHg3"}],27:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("./_input"),s=l["default"].PropTypes,a=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement(o.TextField,this.props)}}]),t}(l["default"].Component);a.propTypes={type:s.oneOf(["text","email","url","tel","password"])},a.defaultProps={type:"text"},r["default"]=a,t.exports=r["default"]},{"./_input":6,react:"CwoHg3"}],28:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=window.React,l=babelHelpers.interopRequireDefault(n),o=e("./_input"),s=l["default"].PropTypes,a=function(e){function t(){return babelHelpers.classCallCheck(this,t),babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(t).apply(this,arguments))}return babelHelpers.inherits(t,e),babelHelpers.createClass(t,[{key:"render",value:function(){return l["default"].createElement(o.TextField,this.props)}}]),t}(l["default"].Component);a.propTypes={rows:s.number},a.defaultProps={type:"textarea",rows:2},r["default"]=a,t.exports=r["default"]},{"./_input":6,react:"CwoHg3"}]},{},[1]);
src/components/setting/listenServer.js
lleohao/meow-ui
import React, { Component } from 'react'; import { Button, Modal, Form, Input, Radio } from 'antd'; import { EditeableList } from '../common'; const FormItem = Form.Item; class ListenServerForm extends Component { changeProtocol = e => { const value = e.target.value; this.props.onChangeProtocol(value); }; render() { const { server, form } = this.props; const { getFieldDecorator } = form; const certAndKeyFormItem = []; if (server.protocol === 'https') { certAndKeyFormItem.push( <FormItem label="cert" key={'cert'}> {getFieldDecorator('cert', { rules: [ { required: true, message: '证书地址为必填项, 且必须是绝对路径' } ], initialValue: server.cert })(<Input placeholder="以绝对路径的方式输入证书地址" />)} </FormItem>, <FormItem label="key" key={'key'}> {getFieldDecorator('key', { rules: [ { required: true, message: '密钥地址为必填项, 且必须是绝对路径' } ], initialValue: server.key })(<Input placeholder="以绝对路径的方式输入密钥地址" />)} </FormItem> ); } return ( <Form layout="vertical"> <FormItem label="服务协议"> {getFieldDecorator('protocol', { initialValue: server.protocol })( <Radio.Group onChange={this.changeProtocol}> <Radio value="http">http</Radio> <Radio value="https">https</Radio> </Radio.Group> )} </FormItem> <FormItem label="地址"> {getFieldDecorator('address', { rules: [ { required: true, message: '代理地址为必填项' } ], initialValue: server.address })(<Input placeholder="127.0.0.1" />)} </FormItem> <FormItem label="端口"> {getFieldDecorator('port', { rules: [ { required: true, message: '代理端口是必填项, 且必须为数字' } ], initialValue: server.port })(<Input placeholder="4411" />)} </FormItem> {certAndKeyFormItem} </Form> ); } } const WrappedListenServerForm = Form.create()(ListenServerForm); export class ListenServerSetting extends Component { defaultServer = { address: '127.0.0.1', port: '4411', protocol: 'http' }; state = { visible: false, inEdit: false, index: null, server: {} }; showModal = () => { this.setState({ visible: true, server: Object.assign({}, this.defaultServer) }); }; handleCancel = () => { const form = this.form; form.resetFields(); this.setState({ visible: false, index: null, inEdit: false }); }; handleCreate = () => { const form = this.form; form.validateFields((err, values) => { if (err) { return; } if (this.state.inEdit) { this.props.onEdit(this.state.index, values); } else { this.props.onAddServer(values); } form.resetFields(); this.setState({ visible: false }); }); }; saveFormRef = form => { this.form = form; }; editServer = index => { const serverList = Array.from(this.props.listenServerList); this.setState({ visible: true, inEdit: true, index: index, server: Object.assign({}, serverList[index]) }); }; changeProtocol = protocol => { this.setState({ server: Object.assign({}, this.state.server, { protocol }) }); }; render() { const list = this.props.listenServerList.map(listenServer => { const { protocol, address, port } = listenServer; return `${protocol}://${address}:${port}`; }); return ( <div className="group"> <h2 className="title"> 监听服务器 <Button className="add-icon no-border" icon="plus" onClick={this.showModal} /> </h2> <EditeableList list={list} onDelete={index => { this.props.onDelete(index); }} onEdit={this.editServer} /> <Modal title="新建监听服务器" visible={this.state.visible} onCancel={this.handleCancel} onOk={this.handleCreate} > <WrappedListenServerForm ref={this.saveFormRef} onChangeProtocol={this.changeProtocol} server={this.state.server} /> </Modal> </div> ); } }
examples/async/index.js
keyanzhang/redux
import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import App from './containers/App' import configureStore from './store/configureStore' const store = configureStore() render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
ajax/libs/angular.js/1.1.5/angular-scenario.js
bergie/cdnjs
/*! * jQuery JavaScript Library v1.8.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Thu Sep 20 2012 21:13:05 GMT-0400 (Eastern Daylight Time) */ (function( window, undefined ) { 'use strict'; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, navigator = window.navigator, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Save a reference to some core methods core_push = Array.prototype.push, core_slice = Array.prototype.slice, core_indexOf = Array.prototype.indexOf, core_toString = Object.prototype.toString, core_hasOwn = Object.prototype.hasOwnProperty, core_trim = String.prototype.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, // Used for detecting and trimming whitespace core_rnotwhite = /\S/, core_rspace = /\s+/, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // The ready event handler and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context && context.nodeType ? context.ownerDocument || context : document ); // scripts is true for back-compat selector = jQuery.parseHTML( match[1], doc, true ); if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { this.attr.call( selector, context, true ); } return jQuery.merge( this, selector ); // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.8.2", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ), "slice", core_slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ core_toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // scripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, scripts ) { var parsed; if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { scripts = context; context = 0; } context = context || document; // Single tag if ( (parsed = rsingleTag.exec( data )) ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); return jQuery.merge( [], (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && core_rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var name, i = 0, length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); if ( args ) { if ( isObj ) { for ( name in obj ) { if ( callback.apply( obj[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( obj[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in obj ) { if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var type, ret = results || []; if ( arr != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 type = jQuery.type( arr ); if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { core_push.call( ret, arr ); } else { jQuery.merge( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready, 1 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.split( core_rspace ), function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" && ( !options.unique || !self.has( arg ) ) ) { list.push( arg ); } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? function() { var returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } } : newDefer[ action ] ); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] = list.fire deferred[ tuple[0] ] = list.fire; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div"); // Preliminary tests div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Can't get basic test support if ( !all || !all.length ) { return {}; } // First batch of supports tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form(#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: ( document.compatMode === "CSS1Compat" ), // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", clickFn = function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent("onclick"); div.detachEvent( "onclick", clickFn ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; input.setAttribute( "checked", "checked" ); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Run tests that need a body at doc ready jQuery(function() { var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = document.createElement("div"); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; div.appendChild( marginDiv ); support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); container.style.zoom = 1; } // Null elements to avoid leaks in IE body.removeChild( container ); container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE fragment.removeChild( div ); all = a = select = opt = input = fragment = div = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // Remove at next major release (1.9/2.0) uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery.removeData( elem, type + "queue", true ); jQuery.removeData( elem, key, true ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, fixSpecified, rclass = /[\t\r\n]/g, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea|)$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var removes, className, elem, c, cl, i, l; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { removes = ( value || "" ).split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { className = (" " + elem.className + " ").replace( rclass, " " ); // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } elem.className = value ? jQuery.trim( className ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( core_rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, i, max, option, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 attrFn: {}, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.split( core_rspace ); for ( ; i < attrNames.length; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.value = value + "" ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, "events", true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event, namespaces = []; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; for ( old = elem; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old === (elem.ownerDocument || document) ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = core_slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) event.metaKey = !!event.metaKey; return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 – // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "_submit_attached" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "_submit_attached", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "_change_attached", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var cachedruns, assertGetIdNotName, Expr, getText, isXML, contains, compile, sortOrder, hasDuplicate, outermostContext, baseHasDuplicate = true, strundefined = "undefined", expando = ( "sizcache" + Math.random() ).replace( ".", "" ), Token = String, document = window.document, docElem = document.documentElement, dirruns = 0, done = 0, pop = [].pop, push = [].push, slice = [].slice, // Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Augment a function for special use by Sizzle markFunction = function( fn, value ) { fn[ expando ] = value == null || value; return fn; }, createCache = function() { var cache = {}, keys = []; return markFunction(function( key, value ) { // Only keep the most recent entries if ( keys.push( key ) > Expr.cacheLength ) { delete cache[ keys.shift() ]; } return (cache[ key ] = value); }, cache ); }, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", // For matchExpr.POS and matchExpr.needsContext pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, rnot = /^:not/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, rheader = /h\d/i, rinputs = /input|select|textarea|button/i, rbackslash = /\\(?!\\)/g, matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "POS": new RegExp( pos, "i" ), "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, // Support // Used for testing something on an element assert = function( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } }, // Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }), // Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }), // Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }), // Check if getElementsByClassName can be trusted assertUsableClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }), // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // If slice is not available, provide a backup try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } function Sizzle( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( !selector || typeof selector !== "string" ) { return results; } if ( nodeType !== 1 && nodeType !== 9 ) { return []; } xml = isXML( context ); if ( !xml && !seed ) { if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); } Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes } else { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } return ret; }; isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Element contains another contains = Sizzle.contains = docElem.contains ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); } : docElem.compareDocumentPosition ? function( a, b ) { return b && !!( a.compareDocumentPosition( b ) & 16 ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; Sizzle.attr = function( elem, name ) { var val, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( xml || assertAttributes ) { return elem.getAttribute( name ); } val = elem.getAttributeNode( name ); return val ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, // IE6/7 return a modified href attrHandle: assertHrefNotNormalized ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }, find: { "ID": assertGetIdNotName ? function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } } : function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }, "TAG": assertTagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { var elem, tmp = [], i = 0; for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }, "NAME": assertUsableName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }, "CLASS": assertUsableClassName && function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } } }, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( rbackslash, "" ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1] === "nth" ) { // nth-child requires argument if ( !match[2] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); // other types prohibit arguments } else if ( match[2] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var unquoted, excess; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } if ( match[3] ) { match[2] = match[3]; } else if ( (unquoted = match[4]) ) { // Only check arguments that contain a pseudo if ( rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index unquoted = unquoted.slice( 0, excess ); match[0] = match[0].slice( 0, excess ); } match[2] = unquoted; } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "ID": assertGetIdNotName ? function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { return elem.getAttribute("id") === id; }; } : function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ expando ][ className ]; if ( !pattern ) { pattern = classCache( className, new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)") ); } return function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }; }, "ATTR": function( name, operator, check ) { return function( elem, context ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { return function( elem ) { var node, diff, parent = elem.parentNode; if ( first === 1 && last === 0 ) { return true; } if ( parent ) { diff = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { diff++; if ( elem === node ) { break; } } } } // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); }; } return function( elem ) { var node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while ( elem ) { if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { return false; } elem = elem.nextSibling; } return true; }, "header": function( elem ) { return rheader.test( elem.nodeName ); }, "text": function( elem ) { var type, attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); }, // Input types "radio": createInputPseudo("radio"), "checkbox": createInputPseudo("checkbox"), "file": createInputPseudo("file"), "password": createInputPseudo("password"), "image": createInputPseudo("image"), "submit": createButtonPseudo("submit"), "reset": createButtonPseudo("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "focus": function( elem ) { var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; }, // Positional types "first": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = 0; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = 1; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; function siblingCheck( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; } sortOrder = docElem.compareDocumentPosition ? function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; } : function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort( sortOrder ); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, i = 1; hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } return results; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ expando ][ selector ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { soFar = soFar.slice( match[0].length ); } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); // Cast descendant combinators to space matched.type = match[0].replace( rtrim, " " ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || // The last two arguments here are (context, xml) for backCompat (match = preFilters[ type ]( match, document, true ))) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); matched.type = type; matched.matches = match; } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && combinator.dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( !xml ) { var cache, dirkey = dirruns + " " + doneName + " ", cachedkey = dirkey + cachedruns; while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( (cache = elem[ expando ]) === cachedkey ) { return elem.sizset; } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { if ( elem.sizset ) { return elem; } } else { elem[ expando ] = cachedkey; if ( matcher( elem, context, xml ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } } else { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( matcher( elem, context, xml ) ) { return elem; } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { // Positional selectors apply to seed elements, so it is invalid to follow them with relative ones if ( seed && postFinder ) { return; } var i, elem, postFilterIn, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [], seed ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { postFilterIn = condense( matcherOut, postMap ); postFilter( postFilterIn, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = postFilterIn.length; while ( i-- ) { if ( (elem = postFilterIn[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } // Keep seed and results synchronized if ( seed ) { // Ignore postFinder because it can't coexist with seed i = preFilter && matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { seed[ preMap[i] ] = !(results[ preMap[i] ] = elem); } } } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { // The concatenated values are (context, xml) for backCompat matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && tokens.join("") ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = superMatcher.el; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); j++ ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { for ( j = 0; (matcher = setMatchers[j]); j++ ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; superMatcher.el = 0; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ expando ][ selector ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results, seed ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results, seed ); } return results; } function select( selector, context, results, seed, xml ) { var i, tokens, token, type, find, match = tokenize( selector ), j = match.length; if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !xml && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } // Fetch a seed set for right-to-left matching for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( rbackslash, "" ), rsibling.test( tokens[0].type ) && context.parentNode || context, xml )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && tokens.join(""); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, xml, results, rsibling.test( selector ) ); return results; } if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // qSa(:focus) reports false when true (Chrome 21), // A support test would require too much code (would include document ready) rbuggyQSA = [":focus"], // matchesSelector(:focus) reports false when true (Chrome 21), // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [ ":active", ":focus" ], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here (do not put tests after this one) if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if ( div.querySelectorAll("[test^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); // rbuggyQSA always contains :focus, so no need for a length check rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if ( !seed && !xml && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { var groups, i, old = true, nid = expando, newContext = context, newSelector = context.nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + groups[i].join(""); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } return oldSelect( selector, context, results, seed, xml ); }; if ( matches ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); rbuggyMatches.push( "!=", pseudos ); } catch ( e ) {} }); // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && (!rbuggyQSA || !rbuggyQSA.test( expr )) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, null, null, [ elem ] ).length > 0; }; } })(); } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, l, length, n, r, ret, self = this; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } ret = this.pushStack( "", "find", selector ); for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rcheckableType = /^(?:checkbox|radio)$/, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "X<div>", "</div>" ]; } jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); } }, after: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { if ( !isDisconnected( this[0] ) ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = [].concat.apply( [], args ); var results, first, fragment, iNoClone, i = 0, value = args[0], scripts = [], l = this.length; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call( this, i, table ? self.html() : undefined ); self.domManip( args, table, callback ); }); } if ( this[0] ) { results = jQuery.buildFragment( args, this, scripts ); fragment = results.fragment; first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). // Fragments from the fragment cache must always be cloned and never used in place. for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], i === iNoClone ? fragment : jQuery.clone( fragment, true, true ) ); } } // Fix #11809: Avoid leaking memory fragment = first = null; if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { if ( jQuery.ajax ) { jQuery.ajax({ url: elem.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.error("no ajax"); } } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); if ( nodeName === "object" ) { // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, context, scripts ) { var fragment, cacheable, cachehit, first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { // Mark cacheable and look for a hit cacheable = true; fragment = jQuery.fragments[ first ]; cachehit = fragment !== undefined; } if ( !fragment ) { fragment = context.createDocumentFragment(); jQuery.clean( args, context, fragment, scripts ); // Update the cache, but only store false // unless this is a second parsing of the same content if ( cacheable ) { jQuery.fragments[ first ] = cachehit && fragment; } } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), l = insert.length, parent = this.length === 1 && this[0].parentNode; if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( ; i < l; i++ ) { elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, clone; if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, safe = context === document && safeFragment, ret = []; // Ensure that context is a document if ( !context || typeof context.createDocumentFragment === "undefined" ) { context = document; } // Use the already-created safe fragment if context permits for ( i = 0; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); div = context.createElement("div"); safe.appendChild( div ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Go to html and back, then peel off extra wrappers tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; depth = wrap[0]; div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> hasBody = rtbody.test(elem); tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Take out of fragment container (we need a fresh div each time) div.parentNode.removeChild( div ); } } if ( elem.nodeType ) { ret.push( elem ); } else { jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { elem = div = safe = null; } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { for ( i = 0; (elem = ret[i]) != null; i++ ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } } // Append elements to a provided document fragment if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } jQuery.deletedIds.push( id ); } } } } } }); // Limit scope pollution from any deprecated API (function() { var matched, browser; // Use of jQuery.browser is frowned upon. // More details: http://api.jquery.com/jQuery.browser // jQuery.uaMatch maintained for back-compat jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }; })(); var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), elemdisplay = {}, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], eventsToggle = jQuery.fn.toggle; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var elem, display, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { display = curCSS( elem, "display" ); if ( !values[ index ] && display !== "none" ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state, fn2 ) { var bool = typeof state === "boolean"; if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { return eventsToggle.apply( this, arguments ); } return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, numeric, extra ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( numeric || extra !== undefined ) { num = parseFloat( val ); return numeric || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, computed = window.getComputedStyle( elem, null ), style = elem.style; if ( computed ) { ret = computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { curCSS = function( elem, name ) { var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { // we use jQuery.css instead of curCSS here // because of the reliableMarginRight CSS hook! val += jQuery.css( elem, extra + cssExpand[ i ], true ); } // From this point on we use curCSS for maximum performance (relevant in animations) if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } else { // at this point, extra isn't content, so add padding val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, valueIsBorderBox = true, isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { if ( elemdisplay[ nodeName ] ) { return elemdisplay[ nodeName ]; } var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), display = elem.css("display"); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // Use the already-created iframe if possible iframe = document.body.appendChild( iframe || jQuery.extend( document.createElement("iframe"), { frameBorder: 0, width: 0, height: 0 }) ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write("<!doctype html><html><body>"); iframeDoc.close(); } elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); display = curCSS( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } else { return getWidthOrHeight( elem, name, extra ); } } }, set: function( elem, value, extra ) { return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "marginRight" ); } }); } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { var ret = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rselectTextarea = /^(?:select|textarea)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), i = 0, length = dataTypes.length; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var selection, list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ); for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } // Don't do a request if no elements are being requested if ( !this.length ) { return this; } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // Request the remote document jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params, complete: function( jqXHR, status ) { if ( callback ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); } } }).done(function( responseText ) { // Save response for use in complete callback response = arguments; // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append( responseText.replace( rscript, "" ) ) // Locate the specified elements .find( selector ) : // If not, just inject the full result responseText ); }); return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // ifModified key ifModifiedKey, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || strAbort; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ ifModifiedKey ] = modified; } modified = jqXHR.getResponseHeader("Etag"); if ( modified ) { jQuery.etag[ ifModifiedKey ] = modified; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.always( tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ) || false; s.crossDomain = parts && ( parts.join(":") + ( parts[ 3 ] ? "" : parts[ 1 ] === "http:" ? 80 : 443 ) ) !== ( ajaxLocParts.join(":") + ( ajaxLocParts[ 3 ] ? "" : ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv, conv2, current, tmp, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ], converters = {}, i = 0; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } var oldCallbacks = [], rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/, nonce = jQuery.now(); // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, data = s.data, url = s.url, hasCallback = s.jsonp !== false, replaceInUrl = hasCallback && rjsonp.test( url ), replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( data ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; overwritten = window[ callbackName ]; // Insert callback into url or form data if ( replaceInUrl ) { s.url = url.replace( rjsonp, "$1" + callbackName ); } else if ( replaceInData ) { s.data = data.replace( rjsonp, "$1" + callbackName ); } else if ( hasCallback ) { s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var xhrCallbacks, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( _ ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback, 0 ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }, 0 ); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, index = 0, tweenerIndex = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), percent = 1 - ( remaining / animation.duration || 0 ), index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end, easing ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { anim: animation, queue: animation.opts.queue, elem: elem }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { var index, prop, value, length, dataShow, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.done(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery.removeData( elem, "fxshow", true ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing any value as a 4th parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, false, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" || // special check for .toggle( handler, handler, ... ) ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations resolve immediately if ( empty ) { anim.stop( true ); } }; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) && !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.interval = 13; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } var rroot = /^(?:body|html)$/i; jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } if ( (body = doc.body) === elem ) { return jQuery.offset.bodyOffset( elem ); } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== "undefined" ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.body; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, value, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window ); /** * @license AngularJS v1.1.5 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, document){ var _jQuery = window.jQuery.noConflict(true); //////////////////////////////////// /** * @ngdoc function * @name angular.lowercase * @function * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; /** * @ngdoc function * @name angular.uppercase * @function * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; var manualLowercase = function(s) { return isString(s) ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);}) : s; }; var manualUppercase = function(s) { return isString(s) ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);}) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods // with correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } var /** holds major version number for IE or NaN for real browsers */ msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]), jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, push = [].push, toString = Object.prototype.toString, _angular = window.angular, /** @name angular */ angular = window.angular || (window.angular = {}), angularModule, nodeName_, uid = ['0', '0', '0']; /** * @ngdoc function * @name angular.noConflict * @function * * @description * Restores the previous global value of angular and returns the current instance. Other libraries may already use the * angular namespace. Or a previous version of angular is already loaded on the page. In these cases you may want to * restore the previous namespace and keep a reference to angular. * * @return {Object} The current angular namespace */ function noConflict() { var a = window.angular; window.angular = _angular; return a; } /** * @private * @param {*} obj * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, ...) */ function isArrayLike(obj) { if (!obj || (typeof obj.length !== 'number')) return false; // We have on object which has length property. Should we treat it as array? if (typeof obj.hasOwnProperty != 'function' && typeof obj.constructor != 'function') { // This is here for IE8: it is a bogus object treat it as array; return true; } else { return obj instanceof JQLite || // JQLite (jQuery && obj instanceof jQuery) || // jQuery toString.call(obj) !== '[object Object]' || // some browser native object typeof obj.callee === 'function'; // arguments (on IE8 looks like regular obj) } } /** * @ngdoc function * @name angular.forEach * @function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` * is the value of an object property or an array element and `key` is the object property key or * array element index. Specifying a `context` for the function is optional. * * Note: this function was previously known as `angular.foreach`. * <pre> var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key){ this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender:male']); </pre> * * @param {Object|Array} obj Object to iterate over. * @param {Function} iterator Iterator function. * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ function forEach(obj, iterator, context) { var key; if (obj) { if (isFunction(obj)){ for (key in obj) { if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context); } else if (isArrayLike(obj)) { for (key = 0; key < obj.length; key++) iterator.call(context, obj[key], key); } else { for (key in obj) { if (obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } } return obj; } function sortedKeys(obj) { var keys = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key); } } return keys.sort(); } function forEachSorted(obj, iterator, context) { var keys = sortedKeys(obj); for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } /** * when using forEach the params are value, key, but it is often useful to have key, value. * @param {function(string, *)} iteratorFn * @returns {function(*, string)} */ function reverseParams(iteratorFn) { return function(value, key) { iteratorFn(key, value) }; } /** * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric * characters such as '012ABC'. The reason why we are not using simply a number counter is that * the number string gets longer over time, and it can also overflow, where as the nextId * will grow much slower, it is a string, and it will never overflow. * * @returns an unique alpha-numeric string */ function nextUid() { var index = uid.length; var digit; while(index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); } /** * Set or clear the hashkey for an object. * @param obj object * @param h the hashkey (!truthy to delete the hashkey) */ function setHashKey(obj, h) { if (h) { obj.$$hashKey = h; } else { delete obj.$$hashKey; } } /** * @ngdoc function * @name angular.extend * @function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). * @returns {Object} Reference to `dst`. */ function extend(dst) { var h = dst.$$hashKey; forEach(arguments, function(obj){ if (obj !== dst) { forEach(obj, function(value, key){ dst[key] = value; }); } }); setHashKey(dst,h); return dst; } function int(str) { return parseInt(str, 10); } function inherit(parent, extra) { return extend(new (extend(function() {}, {prototype:parent}))(), extra); } var START_SPACE = /^\s*/; var END_SPACE = /\s*$/; function stripWhitespace(str) { return isString(str) ? str.replace(START_SPACE, '').replace(END_SPACE, '') : str; } /** * @ngdoc function * @name angular.noop * @function * * @description * A function that performs no operations. This function can be useful when writing code in the * functional style. <pre> function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } </pre> */ function noop() {} noop.$inject = []; /** * @ngdoc function * @name angular.identity * @function * * @description * A function that returns its first argument. This function is useful when writing code in the * functional style. * <pre> function transformer(transformationFn, value) { return (transformationFn || identity)(value); }; </pre> */ function identity($) {return $;} identity.$inject = []; function valueFn(value) {return function() {return value;};} /** * @ngdoc function * @name angular.isUndefined * @function * * @description * Determines if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value){return typeof value == 'undefined';} /** * @ngdoc function * @name angular.isDefined * @function * * @description * Determines if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value){return typeof value != 'undefined';} /** * @ngdoc function * @name angular.isObject * @function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not * considered to be objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value){return value != null && typeof value == 'object';} /** * @ngdoc function * @name angular.isString * @function * * @description * Determines if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value){return typeof value == 'string';} /** * @ngdoc function * @name angular.isNumber * @function * * @description * Determines if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value){return typeof value == 'number';} /** * @ngdoc function * @name angular.isDate * @function * * @description * Determines if a value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value){ return toString.apply(value) == '[object Date]'; } /** * @ngdoc function * @name angular.isArray * @function * * @description * Determines if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ function isArray(value) { return toString.apply(value) == '[object Array]'; } /** * @ngdoc function * @name angular.isFunction * @function * * @description * Determines if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value){return typeof value == 'function';} /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.document && obj.location && obj.alert && obj.setInterval; } function isScope(obj) { return obj && obj.$evalAsync && obj.$watch; } function isFile(obj) { return toString.apply(obj) === '[object File]'; } function isBoolean(value) { return typeof value == 'boolean'; } function trim(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; } /** * @ngdoc function * @name angular.isElement * @function * * @description * Determines if a reference is a DOM element (or wrapped jQuery element). * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). */ function isElement(node) { return node && (node.nodeName // we are a direct element || (node.bind && node.find)); // we have a bind and find method part of jQuery API } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str){ var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } if (msie < 9) { nodeName_ = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML') ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName_ = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function map(obj, iterator, context) { var results = []; forEach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } /** * @description * Determines the number of elements in an array, the number of properties an object has, or * the length of a string. * * Note: This function is used to augment the Object type in Angular expressions. See * {@link angular.Object} for more information about Angular arrays. * * @param {Object|Array|string} obj Object, array, or string to inspect. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. */ function size(obj, ownPropsOnly) { var size = 0, key; if (isArray(obj) || isString(obj)) { return obj.length; } else if (isObject(obj)){ for (key in obj) if (!ownPropsOnly || obj.hasOwnProperty(key)) size++; } return size; } function includes(array, obj) { return indexOf(array, obj) != -1; } function indexOf(array, obj) { if (array.indexOf) return array.indexOf(obj); for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function arrayRemove(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * @ngdoc function * @name angular.copy * @function * * @description * Creates a deep copy of `source`, which should be an object or an array. * * * If no destination is supplied, a copy of the object or array is created. * * If a destination is provided, all of its elements (for array) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array, `source` is returned. * * Note: this function is used to augment the Object type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {*} source The source that will be used to make a copy. * Can be any type, including primitives, `null`, and `undefined`. * @param {(Object|Array)=} destination Destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination`, if `destination` was specified. */ function copy(source, destination){ if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope"); if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isObject(source)) { destination = copy(source, {}); } } } else { if (source === destination) throw Error("Can't copy equivalent objects or arrays"); if (isArray(source)) { destination.length = 0; for ( var i = 0; i < source.length; i++) { destination.push(copy(source[i])); } } else { var h = destination.$$hashKey; forEach(destination, function(value, key){ delete destination[key]; }); for ( var key in source) { destination[key] = copy(source[key]); } setHashKey(destination,h); } } return destination; } /** * Create a shallow copy of an object */ function shallowCopy(src, dst) { dst = dst || {}; for(var key in src) { if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') { dst[key] = src[key]; } } return dst; } /** * @ngdoc function * @name angular.equals * @function * * @description * Determines if two objects or two values are equivalent. Supports value types, arrays and * objects. * * Two objects or values are considered equivalent if at least one of the following is true: * * * Both objects or values pass `===` comparison. * * Both objects or values are of the same type and all of their properties pass `===` comparison. * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal) * * During a property comparison, properties of `function` type and properties with names * that begin with `$` are ignored. * * Scope and DOMWindow objects are being compared only by identify (`===`). * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. */ function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { if ((length = o1.length) == o2.length) { for(key=0; key<length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else if (isDate(o1)) { return isDate(o2) && o1.getTime() == o2.getTime(); } else { if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false; keySet = {}; for(key in o1) { if (key.charAt(0) === '$' || isFunction(o1[key])) continue; if (!equals(o1[key], o2[key])) return false; keySet[key] = true; } for(key in o2) { if (!keySet[key] && key.charAt(0) !== '$' && o2[key] !== undefined && !isFunction(o2[key])) return false; } return true; } } } return false; } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); } function sliceArgs(args, startIndex) { return slice.call(args, startIndex || 0); } /** * @ngdoc function * @name angular.bind * @function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for * `fn`). You can supply optional `args` that are prebound to the function. This feature is also * known as [function currying](http://en.wikipedia.org/wiki/Currying). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) : fn.apply(self, curryArgs); } : function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) return fn; } } function toJsonReplacer(key, value) { var val = value; if (/^\$+/.test(key)) { val = undefined; } else if (isWindow(value)) { val = '$WINDOW'; } else if (value && document === value) { val = '$DOCUMENT'; } else if (isScope(value)) { val = '$SCOPE'; } return val; } /** * @ngdoc function * @name angular.toJson * @function * * @description * Serializes input into a JSON-formatted string. * * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string} Jsonified string representing `obj`. */ function toJson(obj, pretty) { return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); } /** * @ngdoc function * @name angular.fromJson * @function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. * @returns {Object|Array|Date|string|number} Deserialized thingy. */ function fromJson(json) { return isString(json) ? JSON.parse(json) : json; } function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } /** * @returns {string} Returns the string representation of the element. */ function startingTag(element) { element = jqLite(element).clone(); try { // turns out IE does not let you set .html() on elements which // are not allowed to have children. So we just ignore it. element.html(''); } catch(e) {} // As Per DOM Standards var TEXT_NODE = 3; var elemHtml = jqLite('<div>').append(element).html(); try { return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) : elemHtml. match(/^(<[^>]+>)/)[1]. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); } catch(e) { return lowercase(elemHtml); } } ///////////////////////////////////////////////// /** * Parses an escaped url query string into key-value pairs. * @returns Object.<(string|boolean)> */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue){ if (keyValue) { key_value = keyValue.split('='); key = decodeURIComponent(key_value[0]); obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true; } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); }); return parts.length ? parts.join('&') : ''; } /** * We need our custom method because encodeURIComponent is too aggressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); } /** * @ngdoc directive * @name ng.directive:ngApp * * @element ANY * @param {angular.Module} ngApp an optional application * {@link angular.module module} name to load. * * @description * * Use this directive to auto-bootstrap an application. Only * one directive can be used per HTML document. The directive * designates the root of the application and is typically placed * at the root of the page. * * In the example below if the `ngApp` directive would not be placed * on the `html` element then the document would not be compiled * and the `{{ 1+2 }}` would not be resolved to `3`. * * `ngApp` is the easiest way to bootstrap an application. * <doc:example> <doc:source> I can add: 1 + 2 = {{ 1+2 }} </doc:source> </doc:example> * */ function angularInit(element, bootstrap) { var elements = [element], appElement, module, names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/; function append(element) { element && elements.push(element); } forEach(names, function(name) { names[name] = true; append(document.getElementById(name)); name = name.replace(':', '\\:'); if (element.querySelectorAll) { forEach(element.querySelectorAll('.' + name), append); forEach(element.querySelectorAll('.' + name + '\\:'), append); forEach(element.querySelectorAll('[' + name + ']'), append); } }); forEach(elements, function(element) { if (!appElement) { var className = ' ' + element.className + ' '; var match = NG_APP_CLASS_REGEXP.exec(className); if (match) { appElement = element; module = (match[2] || '').replace(/\s+/g, ','); } else { forEach(element.attributes, function(attr) { if (!appElement && names[attr.name]) { appElement = element; module = attr.value; } }); } } }); if (appElement) { bootstrap(appElement, module ? [module] : []); } } /** * @ngdoc function * @name angular.bootstrap * @description * Use this function to manually start up angular application. * * See: {@link guide/bootstrap Bootstrap} * * @param {Element} element DOM element which is the root of angular application. * @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules} * @returns {AUTO.$injector} Returns the newly created injector for this app. */ function bootstrap(element, modules) { var resumeBootstrapInternal = function() { element = jqLite(element); modules = modules || []; modules.unshift(['$provide', function($provide) { $provide.value('$rootElement', element); }]); modules.unshift('ng'); var injector = createInjector(modules); injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animator', function(scope, element, compile, injector, animator) { scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); }); animator.enabled(true); }] ); return injector; }; var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { return resumeBootstrapInternal(); } window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); angular.resumeBootstrap = function(extraModules) { forEach(extraModules, function(module) { modules.push(module); }); resumeBootstrapInternal(); }; } var SNAKE_CASE_REGEXP = /[A-Z]/g; function snake_case(name, separator){ separator = separator || '_'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } function bindJQuery() { // bind to jQuery if present; jQuery = window.jQuery; // reset to jQuery or default to us. if (jQuery) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, controller: JQLitePrototype.controller, injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); JQLitePatchJQueryRemove('remove', true); JQLitePatchJQueryRemove('empty'); JQLitePatchJQueryRemove('html'); } else { jqLite = JQLite; } angular.element = jqLite; } /** * throw error if the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required")); } return arg; } function assertArgFn(arg, name, acceptArrayAnnotation) { if (acceptArrayAnnotation && isArray(arg)) { arg = arg[arg.length - 1]; } assertArg(isFunction(arg), name, 'not a function, got ' + (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg)); return arg; } /** * @ngdoc interface * @name angular.Module * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } return ensure(ensure(window, 'angular', Object), 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @description * * The `angular.module` is a global place for creating and registering Angular modules. All * modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * * # Module * * A module is a collocation of services, directives, filters, and configuration information. Module * is used to configure the {@link AUTO.$injector $injector}. * * <pre> * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }); * </pre> * * Then you can create an injector and load your modules like this: * * <pre> * var injector = angular.injector(['ng', 'MyModule']) * </pre> * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the * the module is being retrieved for further configuration. * @param {Function} configFn Optional configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw Error('No module: ' + name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke'); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @propertyOf angular.Module * @returns {Array.<string>} List of module names which must be loaded before this module. * @description * Holds the list of modules which the injector will load before the current module is loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @propertyOf angular.Module * @returns {string} Name of the module. * @description */ name: name, /** * @ngdoc method * @name angular.Module#provider * @methodOf angular.Module * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the service. * @description * See {@link AUTO.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @methodOf angular.Module * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link AUTO.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @methodOf angular.Module * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link AUTO.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @methodOf angular.Module * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link AUTO.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @methodOf angular.Module * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link AUTO.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#animation * @methodOf angular.Module * @param {string} name animation name * @param {Function} animationFactory Factory function for creating new instance of an animation. * @description * * Defines an animation hook that can be later used with {@link ng.directive:ngAnimate ngAnimate} * alongside {@link ng.directive:ngAnimate#Description common ng directives} as well as custom directives. * <pre> * module.animation('animation-name', function($inject1, $inject2) { * return { * //this gets called in preparation to setup an animation * setup : function(element) { ... }, * * //this gets called once the animation is run * start : function(element, done, memo) { ... } * } * }) * </pre> * * See {@link ng.$animationProvider#register $animationProvider.register()} and * {@link ng.directive:ngAnimate ngAnimate} for more information. */ animation: invokeLater('$animationProvider', 'register'), /** * @ngdoc method * @name angular.Module#filter * @methodOf angular.Module * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @methodOf angular.Module * @param {string} name Controller name. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @methodOf angular.Module * @param {string} name directive name * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link ng.$compileProvider#directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @methodOf angular.Module * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. */ config: config, /** * @ngdoc method * @name angular.Module#run * @methodOf angular.Module * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which should be performed when the injector is done * loading all modules. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod) { return function() { invokeQueue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; } } }); }; }); } /** * @ngdoc property * @name angular.version * @description * An object that contains information about the current AngularJS version. This object has the * following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". * - `minor` – `{number}` – Minor version number, such as "9". * - `dot` – `{number}` – Dot version number, such as "18". * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { full: '1.1.5', // all of these placeholder strings will be replaced by grunt's major: 1, // package task minor: 1, dot: 5, codeName: 'triangle-squarification' }; function publishExternalAPI(angular){ extend(angular, { 'bootstrap': bootstrap, 'copy': copy, 'extend': extend, 'equals': equals, 'element': jqLite, 'forEach': forEach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isElement': isElement, 'isArray': isArray, 'version': version, 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase, 'callbacks': {counter: 0}, 'noConflict': noConflict }); angularModule = setupModuleLoader(window); try { angularModule('ngLocale'); } catch (e) { angularModule('ngLocale', []).provider('$locale', $LocaleProvider); } angularModule('ng', ['ngLocale'], ['$provide', function ngModule($provide) { $provide.provider('$compile', $CompileProvider). directive({ a: htmlAnchorDirective, input: inputDirective, textarea: inputDirective, form: formDirective, script: scriptDirective, select: selectDirective, style: styleDirective, option: optionDirective, ngBind: ngBindDirective, ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective, ngBindTemplate: ngBindTemplateDirective, ngClass: ngClassDirective, ngClassEven: ngClassEvenDirective, ngClassOdd: ngClassOddDirective, ngCsp: ngCspDirective, ngCloak: ngCloakDirective, ngController: ngControllerDirective, ngForm: ngFormDirective, ngHide: ngHideDirective, ngIf: ngIfDirective, ngInclude: ngIncludeDirective, ngInit: ngInitDirective, ngNonBindable: ngNonBindableDirective, ngPluralize: ngPluralizeDirective, ngRepeat: ngRepeatDirective, ngShow: ngShowDirective, ngSubmit: ngSubmitDirective, ngStyle: ngStyleDirective, ngSwitch: ngSwitchDirective, ngSwitchWhen: ngSwitchWhenDirective, ngSwitchDefault: ngSwitchDefaultDirective, ngOptions: ngOptionsDirective, ngView: ngViewDirective, ngTransclude: ngTranscludeDirective, ngModel: ngModelDirective, ngList: ngListDirective, ngChange: ngChangeDirective, required: requiredDirective, ngRequired: requiredDirective, ngValue: ngValueDirective }). directive(ngAttributeAliasDirectives). directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, $animation: $AnimationProvider, $animator: $AnimatorProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, $document: $DocumentProvider, $exceptionHandler: $ExceptionHandlerProvider, $filter: $FilterProvider, $interpolate: $InterpolateProvider, $http: $HttpProvider, $httpBackend: $HttpBackendProvider, $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, $route: $RouteProvider, $routeParams: $RouteParamsProvider, $rootScope: $RootScopeProvider, $q: $QProvider, $sniffer: $SnifferProvider, $templateCache: $TemplateCacheProvider, $timeout: $TimeoutProvider, $window: $WindowProvider }); } ]); } ////////////////////////////////// //JQLite ////////////////////////////////// /** * @ngdoc function * @name angular.element * @function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite * implementation (commonly referred to as jqLite). * * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded` * event fired. * * jqLite is a tiny, API-compatible subset of jQuery that allows * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality * within a very small footprint, so only a subset of the jQuery API - methods, arguments and * invocation styles - are supported. * * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never * raw DOM references. * * ## Angular's jQuery lite provides the following methods: * * - [addClass()](http://api.jquery.com/addClass/) * - [after()](http://api.jquery.com/after/) * - [append()](http://api.jquery.com/append/) * - [attr()](http://api.jquery.com/attr/) * - [bind()](http://api.jquery.com/bind/) - Does not support namespaces * - [children()](http://api.jquery.com/children/) - Does not support selectors * - [clone()](http://api.jquery.com/clone/) * - [contents()](http://api.jquery.com/contents/) * - [css()](http://api.jquery.com/css/) * - [data()](http://api.jquery.com/data/) * - [eq()](http://api.jquery.com/eq/) * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name * - [hasClass()](http://api.jquery.com/hasClass/) * - [html()](http://api.jquery.com/html/) * - [next()](http://api.jquery.com/next/) - Does not support selectors * - [parent()](http://api.jquery.com/parent/) - Does not support selectors * - [prepend()](http://api.jquery.com/prepend/) * - [prop()](http://api.jquery.com/prop/) * - [ready()](http://api.jquery.com/ready/) * - [remove()](http://api.jquery.com/remove/) * - [removeAttr()](http://api.jquery.com/removeAttr/) * - [removeClass()](http://api.jquery.com/removeClass/) * - [removeData()](http://api.jquery.com/removeData/) * - [replaceWith()](http://api.jquery.com/replaceWith/) * - [text()](http://api.jquery.com/text/) * - [toggleClass()](http://api.jquery.com/toggleClass/) * - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. * - [unbind()](http://api.jquery.com/unbind/) - Does not support namespaces * - [val()](http://api.jquery.com/val/) * - [wrap()](http://api.jquery.com/wrap/) * * ## In addition to the above, Angular provides additional methods to both jQuery and jQuery lite: * * - `controller(name)` - retrieves the controller of the current element or its parent. By default * retrieves controller associated with the `ngController` directive. If `name` is provided as * camelCase directive name, then the controller for this directive will be retrieved (e.g. * `'ngModel'`). * - `injector()` - retrieves the injector of the current element or its parent. * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current * element or its parent. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top * parent element is reached. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ var jqCache = JQLite.cache = {}, jqName = JQLite.expando = 'ng-' + new Date().getTime(), jqId = 1, addEventListenerFn = (window.document.addEventListener ? function(element, type, fn) {element.addEventListener(type, fn, false);} : function(element, type, fn) {element.attachEvent('on' + type, fn);}), removeEventListenerFn = (window.document.removeEventListener ? function(element, type, fn) {element.removeEventListener(type, fn, false); } : function(element, type, fn) {element.detachEvent('on' + type, fn); }); function jqNextId() { return ++jqId; } var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; var MOZ_HACK_REGEXP = /^moz([A-Z])/; /** * Converts snake_case to camelCase. * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function camelCase(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); } ///////////////////////////////////////////// // jQuery mutation patch // // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a // $destroy event on all DOM nodes being removed. // ///////////////////////////////////////////// function JQLitePatchJQueryRemove(name, dispatchThis) { var originalJqFn = jQuery.fn[name]; originalJqFn = originalJqFn.$original || originalJqFn; removePatch.$original = originalJqFn; jQuery.fn[name] = removePatch; function removePatch() { var list = [this], fireEvent = dispatchThis, set, setIndex, setLength, element, childIndex, childLength, children, fns, events; while(list.length) { set = list.shift(); for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { element = jqLite(set[setIndex]); if (fireEvent) { element.triggerHandler('$destroy'); } else { fireEvent = !fireEvent; } for(childIndex = 0, childLength = (children = element.children()).length; childIndex < childLength; childIndex++) { list.push(jQuery(children[childIndex])); } } } return originalJqFn.apply(this, arguments); } } ///////////////////////////////////////////// function JQLite(element) { if (element instanceof JQLite) { return element; } if (!(this instanceof JQLite)) { if (isString(element) && element.charAt(0) != '<') { throw Error('selectors not implemented'); } return new JQLite(element); } if (isString(element)) { var div = document.createElement('div'); // Read about the NoScope elements here: // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx div.innerHTML = '<div>&#160;</div>' + element; // IE insanity to make NoScope elements work! div.removeChild(div.firstChild); // remove the superfluous div JQLiteAddNodes(this, div.childNodes); this.remove(); // detach the elements from the temporary DOM div. } else { JQLiteAddNodes(this, element); } } function JQLiteClone(element) { return element.cloneNode(true); } function JQLiteDealoc(element){ JQLiteRemoveData(element); for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { JQLiteDealoc(children[i]); } } function JQLiteUnbind(element, type, fn) { var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); if (!handle) return; //no listeners registered if (isUndefined(type)) { forEach(events, function(eventHandler, type) { removeEventListenerFn(element, type, eventHandler); delete events[type]; }); } else { if (isUndefined(fn)) { removeEventListenerFn(element, type, events[type]); delete events[type]; } else { arrayRemove(events[type], fn); } } } function JQLiteRemoveData(element) { var expandoId = element[jqName], expandoStore = jqCache[expandoId]; if (expandoStore) { if (expandoStore.handle) { expandoStore.events.$destroy && expandoStore.handle({}, '$destroy'); JQLiteUnbind(element); } delete jqCache[expandoId]; element[jqName] = undefined; // ie does not allow deletion of attributes on elements. } } function JQLiteExpandoStore(element, key, value) { var expandoId = element[jqName], expandoStore = jqCache[expandoId || -1]; if (isDefined(value)) { if (!expandoStore) { element[jqName] = expandoId = jqNextId(); expandoStore = jqCache[expandoId] = {}; } expandoStore[key] = value; } else { return expandoStore && expandoStore[key]; } } function JQLiteData(element, key, value) { var data = JQLiteExpandoStore(element, 'data'), isSetter = isDefined(value), keyDefined = !isSetter && isDefined(key), isSimpleGetter = keyDefined && !isObject(key); if (!data && !isSimpleGetter) { JQLiteExpandoStore(element, 'data', data = {}); } if (isSetter) { data[key] = value; } else { if (keyDefined) { if (isSimpleGetter) { // don't create data in this case. return data && data[key]; } else { extend(data, key); } } else { return data; } } } function JQLiteHasClass(element, selector) { return ((" " + element.className + " ").replace(/[\n\t]/g, " "). indexOf( " " + selector + " " ) > -1); } function JQLiteRemoveClass(element, cssClasses) { if (cssClasses) { forEach(cssClasses.split(' '), function(cssClass) { element.className = trim( (" " + element.className + " ") .replace(/[\n\t]/g, " ") .replace(" " + trim(cssClass) + " ", " ") ); }); } } function JQLiteAddClass(element, cssClasses) { if (cssClasses) { forEach(cssClasses.split(' '), function(cssClass) { if (!JQLiteHasClass(element, cssClass)) { element.className = trim(element.className + ' ' + trim(cssClass)); } }); } } function JQLiteAddNodes(root, elements) { if (elements) { elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) ? elements : [ elements ]; for(var i=0; i < elements.length; i++) { root.push(elements[i]); } } } function JQLiteController(element, name) { return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); } function JQLiteInheritedData(element, name, value) { element = jqLite(element); // if element is the document object work with the html element instead // this makes $(document).scope() possible if(element[0].nodeType == 9) { element = element.find('html'); } while (element.length) { if (value = element.data(name)) return value; element = element.parent(); } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } // check if document already is loaded if (document.readyState === 'complete'){ setTimeout(trigger); } else { this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. JQLite(window).bind('load', trigger); // fallback to window.onload for others } }, toString: function() { var value = []; forEach(this, function(e){ value.push('' + e);}); return '[' + value.join(', ') + ']'; }, eq: function(index) { return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// var BOOLEAN_ATTR = {}; forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { BOOLEAN_ATTR[lowercase(value)] = value; }); var BOOLEAN_ELEMENTS = {}; forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { BOOLEAN_ELEMENTS[uppercase(value)] = true; }); function getBooleanAttrName(element, name) { // check dom last since we will most likely fail on name var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; // booleanAttr is here twice to minimize DOM access return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr; } forEach({ data: JQLiteData, inheritedData: JQLiteInheritedData, scope: function(element) { return JQLiteInheritedData(element, '$scope'); }, controller: JQLiteController , injector: function(element) { return JQLiteInheritedData(element, '$injector'); }, removeAttr: function(element,name) { element.removeAttribute(name); }, hasClass: JQLiteHasClass, css: function(element, name, value) { name = camelCase(name); if (isDefined(value)) { element.style[name] = value; } else { var val; if (msie <= 8) { // this is some IE specific weirdness that jQuery 1.6.4 does not sure why val = element.currentStyle && element.currentStyle[name]; if (val === '') val = 'auto'; } val = val || element.style[name]; if (msie <= 8) { // jquery weirdness :-/ val = (val === '') ? undefined : val; } return val; } }, attr: function(element, name, value){ var lowercasedName = lowercase(name); if (BOOLEAN_ATTR[lowercasedName]) { if (isDefined(value)) { if (!!value) { element[name] = true; element.setAttribute(name, lowercasedName); } else { element[name] = false; element.removeAttribute(lowercasedName); } } else { return (element[name] || (element.attributes.getNamedItem(name)|| noop).specified) ? lowercasedName : undefined; } } else if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined var ret = element.getAttribute(name, 2); // normalize non-existing attributes to undefined (as jQuery) return ret === null ? undefined : ret; } }, prop: function(element, name, value) { if (isDefined(value)) { element[name] = value; } else { return element[name]; } }, text: extend((msie < 9) ? function(element, value) { if (element.nodeType == 1 /** Element */) { if (isUndefined(value)) return element.innerText; element.innerText = value; } else { if (isUndefined(value)) return element.nodeValue; element.nodeValue = value; } } : function(element, value) { if (isUndefined(value)) { return element.textContent; } element.textContent = value; }, {$dv:''}), val: function(element, value) { if (isUndefined(value)) { return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { JQLiteDealoc(childNodes[i]); } element.innerHTML = value; } }, function(fn, name){ /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it // in a way that survives minification. if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for(i=0; i < this.length; i++) { if (fn === JQLiteData) { // data() takes the whole object in jQuery fn(this[i], arg1); } else { for (key in arg1) { fn(this[i], key, arg1[key]); } } } // return self for chaining return this; } else { // we are a read, so read the first child. if (this.length) return fn(this[0], arg1, arg2); } } else { // we are a write, so apply to all children for(i=0; i < this.length; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } return fn.$dv; }; }); function createEventHandler(element, events) { var eventHandler = function (event, type) { if (!event.preventDefault) { event.preventDefault = function() { event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } if (!event.target) { event.target = event.srcElement || document; } if (isUndefined(event.defaultPrevented)) { var prevent = event.preventDefault; event.preventDefault = function() { event.defaultPrevented = true; prevent.call(event); }; event.defaultPrevented = false; } event.isDefaultPrevented = function() { return event.defaultPrevented || event.returnValue == false; }; forEach(events[type || event.type], function(fn) { fn.call(element, event); }); // Remove monkey-patched methods (IE), // as they would cause memory leaks in IE8. if (msie <= 8) { // IE7/8 does not allow to delete property on native object event.preventDefault = null; event.stopPropagation = null; event.isDefaultPrevented = null; } else { // It shouldn't affect normal browsers (native methods are defined on prototype). delete event.preventDefault; delete event.stopPropagation; delete event.isDefaultPrevented; } }; eventHandler.elem = element; return eventHandler; } ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: JQLiteRemoveData, dealoc: JQLiteDealoc, bind: function bindFn(element, type, fn){ var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); if (!events) JQLiteExpandoStore(element, 'events', events = {}); if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); forEach(type.split(' '), function(type){ var eventFns = events[type]; if (!eventFns) { if (type == 'mouseenter' || type == 'mouseleave') { var contains = document.body.contains || document.body.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; events[type] = []; // Refer to jQuery's implementation of mouseenter & mouseleave // Read about mouseenter and mouseleave: // http://www.quirksmode.org/js/events_mouse.html#link8 var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"} bindFn(element, eventmap[type], function(event) { var ret, target = this, related = event.relatedTarget; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !contains(target, related)) ){ handle(event, type); } }); } else { addEventListenerFn(element, type, handle); events[type] = []; } eventFns = events[type] } eventFns.push(fn); }); }, unbind: JQLiteUnbind, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; JQLiteDealoc(element); forEach(new JQLite(replaceNode), function(node){ if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element){ if (element.nodeType === 1) children.push(element); }); return children; }, contents: function(element) { return element.childNodes || []; }, append: function(element, node) { forEach(new JQLite(node), function(child){ if (element.nodeType === 1 || element.nodeType === 11) { element.appendChild(child); } }); }, prepend: function(element, node) { if (element.nodeType === 1) { var index = element.firstChild; forEach(new JQLite(node), function(child){ if (index) { element.insertBefore(child, index); } else { element.appendChild(child); index = child; } }); } }, wrap: function(element, wrapNode) { wrapNode = jqLite(wrapNode)[0]; var parent = element.parentNode; if (parent) { parent.replaceChild(wrapNode, element); } wrapNode.appendChild(element); }, remove: function(element) { JQLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); }, after: function(element, newElement) { var index = element, parent = element.parentNode; forEach(new JQLite(newElement), function(node){ parent.insertBefore(node, index.nextSibling); index = node; }); }, addClass: JQLiteAddClass, removeClass: JQLiteRemoveClass, toggleClass: function(element, selector, condition) { if (isUndefined(condition)) { condition = !JQLiteHasClass(element, selector); } (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, next: function(element) { if (element.nextElementSibling) { return element.nextElementSibling; } // IE8 doesn't have nextElementSibling var elm = element.nextSibling; while (elm != null && elm.nodeType !== 1) { elm = elm.nextSibling; } return elm; }, find: function(element, selector) { return element.getElementsByTagName(selector); }, clone: JQLiteClone, triggerHandler: function(element, eventName) { var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName]; var event; forEach(eventFns, function(fn) { fn.call(element, {preventDefault: noop}); }); } }, function(fn, name){ /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2) { var value; for(var i=0; i < this.length; i++) { if (value == undefined) { value = fn(this[i], arg1, arg2); if (value !== undefined) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { JQLiteAddNodes(value, fn(this[i], arg1, arg2)); } } return value == undefined ? this : value; }; }); /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either result of calling $$hashKey function on the object or uniquely generated id, * that is also assigned to the $$hashKey property of the object. * * @param obj * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ function hashKey(obj) { var objType = typeof obj, key; if (objType == 'object' && obj !== null) { if (typeof (key = obj.$$hashKey) == 'function') { // must invoke on object to keep the right this key = obj.$$hashKey(); } else if (key === undefined) { key = obj.$$hashKey = nextUid(); } } else { key = obj; } return objType + ':' + key; } /** * HashMap which can use objects as keys */ function HashMap(array){ forEach(array, this.put, this); } HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[hashKey(key)] = value; }, /** * @param key * @returns the value for the key */ get: function(key) { return this[hashKey(key)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = hashKey(key)]; delete this[key]; return value; } }; /** * @ngdoc function * @name angular.injector * @function * * @description * Creates an injector function that can be used for retrieving services as well as for * dependency injection (see {@link guide/di dependency injection}). * * @param {Array.<string|Function>} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. * @returns {function()} Injector function. See {@link AUTO.$injector $injector}. * * @example * Typical usage * <pre> * // create an injector * var $injector = angular.injector(['ng']); * * // use the injector to kick off your application * // use the type inference to auto inject arguments, or use implicit injection * $injector.invoke(function($rootScope, $compile, $document){ * $compile($document)($rootScope); * $rootScope.$digest(); * }); * </pre> */ /** * @ngdoc overview * @name AUTO * @description * * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}. */ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; function annotate(fn) { var $inject, fnText, argDecl, last; if (typeof fn == 'function') { if (!($inject = fn.$inject)) { $inject = []; fnText = fn.toString().replace(STRIP_COMMENTS, ''); argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, underscore, name){ $inject.push(name); }); }); fn.$inject = $inject; } } else if (isArray(fn)) { last = fn.length - 1; assertArgFn(fn[last], 'fn'); $inject = fn.slice(0, last); } else { assertArgFn(fn, 'fn', true); } return $inject; } /////////////////////////////////////// /** * @ngdoc object * @name AUTO.$injector * @function * * @description * * `$injector` is used to retrieve object instances as defined by * {@link AUTO.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * * <pre> * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); * expect($injector.invoke(function($injector){ * return $injector; * }).toBe($injector); * </pre> * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following are all valid ways of annotating function with injection arguments and are equivalent. * * <pre> * // inferred (only works if code not minified/obfuscated) * $injector.invoke(function(serviceA){}); * * // annotated * function explicit(serviceA) {}; * explicit.$inject = ['serviceA']; * $injector.invoke(explicit); * * // inline * $injector.invoke(['serviceA', function(serviceA){}]); * </pre> * * ## Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition can then be * parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation * tools since these tools change the argument names. * * ## `$inject` Annotation * By adding a `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. */ /** * @ngdoc method * @name AUTO.$injector#get * @methodOf AUTO.$injector * * @description * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. * @return {*} The instance. */ /** * @ngdoc method * @name AUTO.$injector#invoke * @methodOf AUTO.$injector * * @description * Invoke the method and supply the method arguments from the `$injector`. * * @param {!function} fn The function to invoke. The function arguments come form the function annotation. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @returns {*} the value returned by the invoked `fn` function. */ /** * @ngdoc method * @name AUTO.$injector#has * @methodOf AUTO.$injector * * @description * Allows the user to query if the particular service exist. * * @param {string} Name of the service to query. * @returns {boolean} returns true if injector has given service. */ /** * @ngdoc method * @name AUTO.$injector#instantiate * @methodOf AUTO.$injector * @description * Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies * all of the arguments to the constructor function as specified by the constructor annotation. * * @param {function} Type Annotated constructor function. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @returns {Object} new instance of `Type`. */ /** * @ngdoc method * @name AUTO.$injector#annotate * @methodOf AUTO.$injector * * @description * Returns an array of service names which the function is requesting for injection. This API is used by the injector * to determine which services need to be injected into the function when the function is invoked. There are three * ways in which the function can be annotated with the needed dependencies. * * # Argument names * * The simplest form is to extract the dependencies from the arguments of the function. This is done by converting * the function into a string using `toString()` method and extracting the argument names. * <pre> * // Given * function MyController($scope, $route) { * // ... * } * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * </pre> * * This method does not work with code minfication / obfuscation. For this reason the following annotation strategies * are supported. * * # The `$inject` property * * If a function has an `$inject` property and its value is an array of strings, then the strings represent names of * services to be injected into the function. * <pre> * // Given * var MyController = function(obfuscatedScope, obfuscatedRoute) { * // ... * } * // Define function dependencies * MyController.$inject = ['$scope', '$route']; * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * </pre> * * # The array notation * * It is often desirable to inline Injected functions and that's when setting the `$inject` property is very * inconvenient. In these situations using the array notation to specify the dependencies in a way that survives * minification is a better choice: * * <pre> * // We wish to write this (not minification / obfuscation safe) * injector.invoke(function($compile, $rootScope) { * // ... * }); * * // We are forced to write break inlining * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { * // ... * }; * tmpFn.$inject = ['$compile', '$rootScope']; * injector.invoke(tmpFn); * * // To better support inline function the inline annotation is supported * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { * // ... * }]); * * // Therefore * expect(injector.annotate( * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) * ).toEqual(['$compile', '$rootScope']); * </pre> * * @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described * above. * * @returns {Array.<string>} The names of the services which the function requires. */ /** * @ngdoc object * @name AUTO.$provide * * @description * * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance. * The providers share the same name as the instance they create with `Provider` suffixed to them. * * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of * a service. The Provider can have additional methods which would allow for configuration of the provider. * * <pre> * function GreetProvider() { * var salutation = 'Hello'; * * this.salutation = function(text) { * salutation = text; * }; * * this.$get = function() { * return function (name) { * return salutation + ' ' + name + '!'; * }; * }; * } * * describe('Greeter', function(){ * * beforeEach(module(function($provide) { * $provide.provider('greet', GreetProvider); * })); * * it('should greet', inject(function(greet) { * expect(greet('angular')).toEqual('Hello angular!'); * })); * * it('should allow configuration of salutation', function() { * module(function(greetProvider) { * greetProvider.salutation('Ahoj'); * }); * inject(function(greet) { * expect(greet('angular')).toEqual('Ahoj angular!'); * }); * }); * </pre> */ /** * @ngdoc method * @name AUTO.$provide#provider * @methodOf AUTO.$provide * @description * * Register a provider for a service. The providers can be retrieved and can have additional configuration methods. * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#factory * @methodOf AUTO.$provide * @description * * A short hand for configuring services if only `$get` method is required. * * @param {string} name The name of the instance. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for * `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#service * @methodOf AUTO.$provide * @description * * A short hand for registering service of given class. * * @param {string} name The name of the instance. * @param {Function} constructor A class (constructor function) that will be instantiated. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#value * @methodOf AUTO.$provide * @description * * A short hand for configuring services if the `$get` method is a constant. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#constant * @methodOf AUTO.$provide * @description * * A constant value, but unlike {@link AUTO.$provide#value value} it can be injected * into configuration function (other modules) and it is not interceptable by * {@link AUTO.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance */ /** * @ngdoc method * @name AUTO.$provide#decorator * @methodOf AUTO.$provide * @description * * Decoration of service, allows the decorator to intercept the service instance creation. The * returned instance may be the original instance, or a new instance which delegates to the * original instance. * * @param {string} name The name of the service to decorate. * @param {function()} decorator This function will be invoked when the service needs to be * instantiated. The function is called using the {@link AUTO.$injector#invoke * injector.invoke} method and is therefore fully injectable. Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. */ function createInjector(modulesToLoad) { var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap(), providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, providerInjector = (providerCache.$injector = createInternalInjector(providerCache, function() { throw Error("Unknown provider: " + path.join(' <- ')); })), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(servicename) { var provider = providerInjector.get(servicename + providerSuffix); return instanceInjector.invoke(provider.$get, provider); })); forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector; //////////////////////////////////// // $provider //////////////////////////////////// function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } } } function provider(name, provider_) { if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw Error('Provider ' + name + ' must define $get factory method.'); } return providerCache[name + providerSuffix] = provider_; } function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); } function value(name, value) { return factory(name, valueFn(value)); } function constant(name, value) { providerCache[name] = value; instanceCache[name] = value; } function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); }; } //////////////////////////////////// // Module Loading //////////////////////////////////// function loadModules(modulesToLoad){ var runBlocks = []; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); if (isString(module)) { var moduleFn = angularModule(module); runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); try { for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { var invokeArgs = invokeQueue[i], provider = providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isFunction(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isArray(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + String(module[module.length - 1]); throw e; } } else { assertArgFn(module, 'module'); } }); return runBlocks; } //////////////////////////////////// // internal Injector //////////////////////////////////// function createInternalInjector(cache, factory) { function getService(serviceName) { if (typeof serviceName !== 'string') { throw Error('Service name expected'); } if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw Error('Circular dependency: ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName); } finally { path.shift(); } } } function invoke(fn, self, locals){ var args = [], $inject = annotate(fn), length, i, key; for(i = 0, length = $inject.length; i < length; i++) { key = $inject[i]; args.push( locals && locals.hasOwnProperty(key) ? locals[key] : getService(key) ); } if (!fn.$inject) { // this means that we must be an array. fn = fn[length]; } // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke switch (self ? -1 : args.length) { case 0: return fn(); case 1: return fn(args[0]); case 2: return fn(args[0], args[1]); case 3: return fn(args[0], args[1], args[2]); case 4: return fn(args[0], args[1], args[2], args[3]); case 5: return fn(args[0], args[1], args[2], args[3], args[4]); case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); default: return fn.apply(self, args); } } function instantiate(Type, locals) { var Constructor = function() {}, instance, returnedValue; // Check if Type is annotated and use just the given function at n-1 as parameter // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; instance = new Constructor(); returnedValue = invoke(Type, instance, locals); return isObject(returnedValue) ? returnedValue : instance; } return { invoke: invoke, instantiate: instantiate, get: getService, annotate: annotate, has: function(name) { return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); } }; } } /** * @ngdoc function * @name ng.$anchorScroll * @requires $window * @requires $location * @requires $rootScope * * @description * When called, it checks current value of `$location.hash()` and scroll to related element, * according to rules specified in * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}. * * It also watches the `$location.hash()` and scroll whenever it changes to match any anchor. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. */ function $AnchorScrollProvider() { var autoScrollingEnabled = true; this.disableAutoScrolling = function() { autoScrollingEnabled = false; }; this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { var document = $window.document; // helper function to get first anchor from a NodeList // can't use filter.filter, as it accepts only instances of Array // and IE can't convert NodeList to an array using [].slice // TODO(vojta): use filter if we change it to accept lists as well function getFirstAnchor(list) { var result = null; forEach(list, function(element) { if (!result && lowercase(element.nodeName) === 'a') result = element; }); return result; } function scroll() { var hash = $location.hash(), elm; // empty hash, scroll to the top of the page if (!hash) $window.scrollTo(0, 0); // element with given id else if ((elm = document.getElementById(hash))) elm.scrollIntoView(); // first anchor with given name :-D else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView(); // no element and hash == 'top', scroll to the top of the page else if (hash === 'top') $window.scrollTo(0, 0); } // does not scroll when user clicks on anchor link that is currently on // (no url change, no $location.hash() change), browser native does scroll if (autoScrollingEnabled) { $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, function autoScrollWatchAction() { $rootScope.$evalAsync(scroll); }); } return scroll; }]; } /** * @ngdoc object * @name ng.$animationProvider * @description * * The $AnimationProvider provider allows developers to register and access custom JavaScript animations directly inside * of a module. * */ $AnimationProvider.$inject = ['$provide']; function $AnimationProvider($provide) { var suffix = 'Animation'; /** * @ngdoc function * @name ng.$animation#register * @methodOf ng.$animationProvider * * @description * Registers a new injectable animation factory function. The factory function produces the animation object which * has these two properties: * * * `setup`: `function(Element):*` A function which receives the starting state of the element. The purpose * of this function is to get the element ready for animation. Optionally the function returns an memento which * is passed to the `start` function. * * `start`: `function(Element, doneFunction, *)` The element to animate, the `doneFunction` to be called on * element animation completion, and an optional memento from the `setup` function. * * @param {string} name The name of the animation. * @param {function} factory The factory function that will be executed to return the animation object. * */ this.register = function(name, factory) { $provide.factory(camelCase(name) + suffix, factory); }; this.$get = ['$injector', function($injector) { /** * @ngdoc function * @name ng.$animation * @function * * @description * The $animation service is used to retrieve any defined animation functions. When executed, the $animation service * will return a object that contains the setup and start functions that were defined for the animation. * * @param {String} name Name of the animation function to retrieve. Animation functions are registered and stored * inside of the AngularJS DI so a call to $animate('custom') is the same as injecting `customAnimation` * via dependency injection. * @return {Object} the animation object which contains the `setup` and `start` functions that perform the animation. */ return function $animation(name) { if (name) { var animationName = camelCase(name) + suffix; if ($injector.has(animationName)) { return $injector.get(animationName); } } }; }]; } // NOTE: this is a pseudo directive. /** * @ngdoc directive * @name ng.directive:ngAnimate * * @description * The `ngAnimate` directive works as an attribute that is attached alongside pre-existing directives. * It effects how the directive will perform DOM manipulation. This allows for complex animations to take place * without burdening the directive which uses the animation with animation details. The built in directives * `ngRepeat`, `ngInclude`, `ngSwitch`, `ngShow`, `ngHide` and `ngView` already accept `ngAnimate` directive. * Custom directives can take advantage of animation through {@link ng.$animator $animator service}. * * Below is a more detailed breakdown of the supported callback events provided by pre-exisitng ng directives: * * | Directive | Supported Animations | * |========================================================== |====================================================| * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move | * | {@link ng.directive:ngView#animations ngView} | enter and leave | * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave | * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave | * | {@link ng.directive:ngIf#animations ngIf} | enter and leave | * | {@link ng.directive:ngShow#animations ngShow & ngHide} | show and hide | * * You can find out more information about animations upon visiting each directive page. * * Below is an example of a directive that makes use of the ngAnimate attribute: * * <pre> * <!-- you can also use data-ng-animate, ng:animate or x-ng-animate as well --> * <ANY ng-directive ng-animate="{event1: 'animation-name', event2: 'animation-name-2'}"></ANY> * * <!-- you can also use a short hand --> * <ANY ng-directive ng-animate=" 'animation' "></ANY> * <!-- which expands to --> * <ANY ng-directive ng-animate="{ enter: 'animation-enter', leave: 'animation-leave', ...}"></ANY> * * <!-- keep in mind that ng-animate can take expressions --> * <ANY ng-directive ng-animate=" computeCurrentAnimation() "></ANY> * </pre> * * The `event1` and `event2` attributes refer to the animation events specific to the directive that has been assigned. * * Keep in mind that if an animation is running, no child element of such animation can also be animated. * * <h2>CSS-defined Animations</h2> * By default, ngAnimate attaches two CSS classes per animation event to the DOM element to achieve the animation. * It is up to you, the developer, to ensure that the animations take place using cross-browser CSS3 transitions as * well as CSS animations. * * The following code below demonstrates how to perform animations using **CSS transitions** with ngAnimate: * * <pre> * <style type="text/css"> * /&#42; * The animate-enter CSS class is the event name that you * have provided within the ngAnimate attribute. * &#42;/ * .animate-enter { * -webkit-transition: 1s linear all; /&#42; Safari/Chrome &#42;/ * -moz-transition: 1s linear all; /&#42; Firefox &#42;/ * -o-transition: 1s linear all; /&#42; Opera &#42;/ * transition: 1s linear all; /&#42; IE10+ and Future Browsers &#42;/ * * /&#42; The animation preparation code &#42;/ * opacity: 0; * } * * /&#42; * Keep in mind that you want to combine both CSS * classes together to avoid any CSS-specificity * conflicts * &#42;/ * .animate-enter.animate-enter-active { * /&#42; The animation code itself &#42;/ * opacity: 1; * } * </style> * * <div ng-directive ng-animate="{enter: 'animate-enter'}"></div> * </pre> * * The following code below demonstrates how to perform animations using **CSS animations** with ngAnimate: * * <pre> * <style type="text/css"> * .animate-enter { * -webkit-animation: enter_sequence 1s linear; /&#42; Safari/Chrome &#42;/ * -moz-animation: enter_sequence 1s linear; /&#42; Firefox &#42;/ * -o-animation: enter_sequence 1s linear; /&#42; Opera &#42;/ * animation: enter_sequence 1s linear; /&#42; IE10+ and Future Browsers &#42;/ * } * &#64-webkit-keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * &#64-moz-keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * &#64-o-keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * &#64keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * </style> * * <div ng-directive ng-animate="{enter: 'animate-enter'}"></div> * </pre> * * ngAnimate will first examine any CSS animation code and then fallback to using CSS transitions. * * Upon DOM mutation, the event class is added first, then the browser is allowed to reflow the content and then, * the active class is added to trigger the animation. The ngAnimate directive will automatically extract the duration * of the animation to determine when the animation ends. Once the animation is over then both CSS classes will be * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end * immediately resulting in a DOM element that is at it's final state. This final state is when the DOM element * has no CSS transition/animation classes surrounding it. * * <h2>JavaScript-defined Animations</h2> * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations to browsers that do not * yet support them, then you can make use of JavaScript animations defined inside of your AngularJS module. * * <pre> * var ngModule = angular.module('YourApp', []); * ngModule.animation('animate-enter', function() { * return { * setup : function(element) { * //prepare the element for animation * element.css({ 'opacity': 0 }); * var memo = "..."; //this value is passed to the start function * return memo; * }, * start : function(element, done, memo) { * //start the animation * element.animate({ * 'opacity' : 1 * }, function() { * //call when the animation is complete * done() * }); * } * } * }); * </pre> * * As you can see, the JavaScript code follows a similar template to the CSS3 animations. Once defined, the animation * can be used in the same way with the ngAnimate attribute. Keep in mind that, when using JavaScript-enabled * animations, ngAnimate will also add in the same CSS classes that CSS-enabled animations do (even if you're not using * CSS animations) to animated the element, but it will not attempt to find any CSS3 transition or animation duration/delay values. * It will instead close off the animation once the provided done function is executed. So it's important that you * make sure your animations remember to fire off the done function once the animations are complete. * * @param {expression} ngAnimate Used to configure the DOM manipulation animations. * */ var $AnimatorProvider = function() { var NG_ANIMATE_CONTROLLER = '$ngAnimateController'; var rootAnimateController = {running:true}; this.$get = ['$animation', '$window', '$sniffer', '$rootElement', '$rootScope', function($animation, $window, $sniffer, $rootElement, $rootScope) { $rootElement.data(NG_ANIMATE_CONTROLLER, rootAnimateController); /** * @ngdoc function * @name ng.$animator * @function * * @description * The $animator.create service provides the DOM manipulation API which is decorated with animations. * * @param {Scope} scope the scope for the ng-animate. * @param {Attributes} attr the attributes object which contains the ngAnimate key / value pair. (The attributes are * passed into the linking function of the directive using the `$animator`.) * @return {object} the animator object which contains the enter, leave, move, show, hide and animate methods. */ var AnimatorService = function(scope, attrs) { var animator = {}; /** * @ngdoc function * @name ng.animator#enter * @methodOf ng.$animator * @function * * @description * Injects the element object into the DOM (inside of the parent element) and then runs the enter animation. * * @param {jQuery/jqLite element} element the element that will be the focus of the enter animation * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the enter animation * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the enter animation */ animator.enter = animateActionFactory('enter', insert, noop); /** * @ngdoc function * @name ng.animator#leave * @methodOf ng.$animator * @function * * @description * Runs the leave animation operation and, upon completion, removes the element from the DOM. * * @param {jQuery/jqLite element} element the element that will be the focus of the leave animation * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the leave animation */ animator.leave = animateActionFactory('leave', noop, remove); /** * @ngdoc function * @name ng.animator#move * @methodOf ng.$animator * @function * * @description * Fires the move DOM operation. Just before the animation starts, the animator will either append it into the parent container or * add the element directly after the after element if present. Then the move animation will be run. * * @param {jQuery/jqLite element} element the element that will be the focus of the move animation * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the move animation * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the move animation */ animator.move = animateActionFactory('move', move, noop); /** * @ngdoc function * @name ng.animator#show * @methodOf ng.$animator * @function * * @description * Reveals the element by setting the CSS property `display` to `block` and then starts the show animation directly after. * * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden */ animator.show = animateActionFactory('show', show, noop); /** * @ngdoc function * @name ng.animator#hide * @methodOf ng.$animator * * @description * Starts the hide animation first and sets the CSS `display` property to `none` upon completion. * * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden */ animator.hide = animateActionFactory('hide', noop, hide); /** * @ngdoc function * @name ng.animator#animate * @methodOf ng.$animator * * @description * Triggers a custom animation event to be executed on the given element * * @param {jQuery/jqLite element} element that will be animated */ animator.animate = function(event, element) { animateActionFactory(event, noop, noop)(element); } return animator; function animateActionFactory(type, beforeFn, afterFn) { return function(element, parent, after) { var ngAnimateValue = scope.$eval(attrs.ngAnimate); var className = ngAnimateValue ? isObject(ngAnimateValue) ? ngAnimateValue[type] : ngAnimateValue + '-' + type : ''; var animationPolyfill = $animation(className); var polyfillSetup = animationPolyfill && animationPolyfill.setup; var polyfillStart = animationPolyfill && animationPolyfill.start; var polyfillCancel = animationPolyfill && animationPolyfill.cancel; if (!className) { beforeFn(element, parent, after); afterFn(element, parent, after); } else { var activeClassName = className + '-active'; if (!parent) { parent = after ? after.parent() : element.parent(); } if ((!$sniffer.transitions && !polyfillSetup && !polyfillStart) || (parent.inheritedData(NG_ANIMATE_CONTROLLER) || noop).running) { beforeFn(element, parent, after); afterFn(element, parent, after); return; } var animationData = element.data(NG_ANIMATE_CONTROLLER) || {}; if(animationData.running) { (polyfillCancel || noop)(element); animationData.done(); } element.data(NG_ANIMATE_CONTROLLER, {running:true, done:done}); element.addClass(className); beforeFn(element, parent, after); if (element.length == 0) return done(); var memento = (polyfillSetup || noop)(element); // $window.setTimeout(beginAnimation, 0); this was causing the element not to animate // keep at 1 for animation dom rerender $window.setTimeout(beginAnimation, 1); } function parseMaxTime(str) { var total = 0, values = isString(str) ? str.split(/\s*,\s*/) : []; forEach(values, function(value) { total = Math.max(parseFloat(value) || 0, total); }); return total; } function beginAnimation() { element.addClass(activeClassName); if (polyfillStart) { polyfillStart(element, done, memento); } else if (isFunction($window.getComputedStyle)) { //one day all browsers will have these properties var w3cAnimationProp = 'animation'; var w3cTransitionProp = 'transition'; //but some still use vendor-prefixed styles var vendorAnimationProp = $sniffer.vendorPrefix + 'Animation'; var vendorTransitionProp = $sniffer.vendorPrefix + 'Transition'; var durationKey = 'Duration', delayKey = 'Delay', animationIterationCountKey = 'IterationCount', duration = 0; //we want all the styles defined before and after var ELEMENT_NODE = 1; forEach(element, function(element) { if (element.nodeType == ELEMENT_NODE) { var w3cProp = w3cTransitionProp, vendorProp = vendorTransitionProp, iterations = 1, elementStyles = $window.getComputedStyle(element) || {}; //use CSS Animations over CSS Transitions if(parseFloat(elementStyles[w3cAnimationProp + durationKey]) > 0 || parseFloat(elementStyles[vendorAnimationProp + durationKey]) > 0) { w3cProp = w3cAnimationProp; vendorProp = vendorAnimationProp; iterations = Math.max(parseInt(elementStyles[w3cProp + animationIterationCountKey]) || 0, parseInt(elementStyles[vendorProp + animationIterationCountKey]) || 0, iterations); } var parsedDelay = Math.max(parseMaxTime(elementStyles[w3cProp + delayKey]), parseMaxTime(elementStyles[vendorProp + delayKey])); var parsedDuration = Math.max(parseMaxTime(elementStyles[w3cProp + durationKey]), parseMaxTime(elementStyles[vendorProp + durationKey])); duration = Math.max(parsedDelay + (iterations * parsedDuration), duration); } }); $window.setTimeout(done, duration * 1000); } else { done(); } } function done() { if(!done.run) { done.run = true; afterFn(element, parent, after); element.removeClass(className); element.removeClass(activeClassName); element.removeData(NG_ANIMATE_CONTROLLER); } } }; } function show(element) { element.css('display', ''); } function hide(element) { element.css('display', 'none'); } function insert(element, parent, after) { if (after) { after.after(element); } else { parent.append(element); } } function remove(element) { element.remove(); } function move(element, parent, after) { // Do not remove element before insert. Removing will cause data associated with the // element to be dropped. Insert will implicitly do the remove. insert(element, parent, after); } }; /** * @ngdoc function * @name ng.animator#enabled * @methodOf ng.$animator * @function * * @param {Boolean=} If provided then set the animation on or off. * @return {Boolean} Current animation state. * * @description * Globally enables/disables animations. * */ AnimatorService.enabled = function(value) { if (arguments.length) { rootAnimateController.running = !value; } return !rootAnimateController.running; }; return AnimatorService; }]; }; /** * ! This is a private undocumented service ! * * @name ng.$browser * @requires $log * @description * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {function()} XHR XMLHttpRequest constructor. * @param {object} $log console.log or an object with the same interface. * @param {object} $sniffer $sniffer service */ function Browser(window, document, $log, $sniffer) { var self = this, rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}; self.isMock = false; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = completeOutstandingRequest; self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; /** * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, sliceArgs(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn){ pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @name ng.$browser#addPollFn * @methodOf ng.$browser * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn){ pollFn(); }); pollTimeout = setTimeout(check, interval); })(); } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var lastBrowserUrl = location.href, baseElement = document.find('base'); /** * @name ng.$browser#url * @methodOf ng.$browser * * @description * GETTER: * Without any argument, this method just returns current value of location.href. * * SETTER: * With at least one argument, this method sets url to new value. * If html5 history api supported, pushState/replaceState is used, otherwise * location.href/location.replace is used. * Returns its own instance to allow chaining * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to change url. * * @param {string} url New url (when used as setter) * @param {boolean=} replace Should new url replace current history record ? */ self.url = function(url, replace) { // setter if (url) { if (lastBrowserUrl == url) return; lastBrowserUrl = url; if ($sniffer.history) { if (replace) history.replaceState(null, '', url); else { history.pushState(null, '', url); // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 baseElement.attr('href', baseElement.attr('href')); } } else { if (replace) location.replace(url); else location.href = url; } return self; // getter } else { // the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 return location.href.replace(/%27/g,"'"); } }; var urlChangeListeners = [], urlChangeInit = false; function fireUrlChange() { if (lastBrowserUrl == self.url()) return; lastBrowserUrl = self.url(); forEach(urlChangeListeners, function(listener) { listener(self.url()); }); } /** * @name ng.$browser#onUrlChange * @methodOf ng.$browser * @TODO(vojta): refactor to use node's syntax for events * * @description * Register callback function that will be called, when url changes. * * It's only called when the url is changed by outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link * * It's not called when url is changed by $browser.url() method * * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to monitor url changes in angular apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange); // hashchange event if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange); // polling else self.addPollFn(fireUrlChange); urlChangeInit = true; } urlChangeListeners.push(callback); return callback; }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /** * Returns current <base href> * (always relative - without domain) * * @returns {string=} */ self.baseHref = function() { var href = baseElement.attr('href'); return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : ''; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; var cookiePath = self.baseHref(); /** * @name ng.$browser#cookies * @methodOf ng.$browser * * @param {string=} name Cookie name * @param {string=} value Cookie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * <ul> * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li> * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li> * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li> * </ul> * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function(name, value) { var cookieLength, cookieArray, cookie, i, index; if (name) { if (value === undefined) { rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: // - 300 cookies // - 20 cookies per unique domain // - 4096 bytes per cookie if (cookieLength > 4096) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies var name = unescape(cookie.substring(0, index)); // the first value that is seen for a cookie is the most // specific one. values for the same cookie name that // follow are for less specific paths. if (lastCookies[name] === undefined) { lastCookies[name] = unescape(cookie.substring(index + 1)); } } } } return lastCookies; } }; /** * @name ng.$browser#defer * @methodOf ng.$browser * @param {function()} fn A function, who's execution should be defered. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchronously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * @name ng.$browser#defer.cancel * @methodOf ng.$browser.defer * * @description * Cancels a defered task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } return false; }; } function $BrowserProvider(){ this.$get = ['$window', '$log', '$sniffer', '$document', function( $window, $log, $sniffer, $document){ return new Browser($window, $document, $log, $sniffer); }]; } /** * @ngdoc object * @name ng.$cacheFactory * * @description * Factory that constructs cache objects. * * * @param {string} cacheId Name or id of the newly created cache. * @param {object=} options Options object that specifies the cache behavior. Properties: * * - `{number=}` `capacity` — turns the cache into LRU cache. * * @returns {object} Newly created cache object with the following set of methods: * * - `{object}` `info()` — Returns id, size, and options of cache. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns it. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. * - `{void}` `removeAll()` — Removes all cached values. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. * */ function $CacheFactoryProvider() { this.$get = function() { var caches = {}; function cacheFactory(cacheId, options) { if (cacheId in caches) { throw Error('cacheId ' + cacheId + ' taken'); } var size = 0, stats = extend({}, options, {id: cacheId}), data = {}, capacity = (options && options.capacity) || Number.MAX_VALUE, lruHash = {}, freshEnd = null, staleEnd = null; return caches[cacheId] = { put: function(key, value) { var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); refresh(lruEntry); if (isUndefined(value)) return; if (!(key in data)) size++; data[key] = value; if (size > capacity) { this.remove(staleEnd.key); } return value; }, get: function(key) { var lruEntry = lruHash[key]; if (!lruEntry) return; refresh(lruEntry); return data[key]; }, remove: function(key) { var lruEntry = lruHash[key]; if (!lruEntry) return; if (lruEntry == freshEnd) freshEnd = lruEntry.p; if (lruEntry == staleEnd) staleEnd = lruEntry.n; link(lruEntry.n,lruEntry.p); delete lruHash[key]; delete data[key]; size--; }, removeAll: function() { data = {}; size = 0; lruHash = {}; freshEnd = staleEnd = null; }, destroy: function() { data = null; stats = null; lruHash = null; delete caches[cacheId]; }, info: function() { return extend({}, stats, {size: size}); } }; /** * makes the `entry` the freshEnd of the LRU linked list */ function refresh(entry) { if (entry != freshEnd) { if (!staleEnd) { staleEnd = entry; } else if (staleEnd == entry) { staleEnd = entry.n; } link(entry.n, entry.p); link(entry, freshEnd); freshEnd = entry; freshEnd.n = null; } } /** * bidirectionally links two entries of the LRU linked list */ function link(nextEntry, prevEntry) { if (nextEntry != prevEntry) { if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify } } } cacheFactory.info = function() { var info = {}; forEach(caches, function(cache, cacheId) { info[cacheId] = cache.info(); }); return info; }; cacheFactory.get = function(cacheId) { return caches[cacheId]; }; return cacheFactory; }; } /** * @ngdoc object * @name ng.$templateCache * * @description * Cache used for storing html templates. * * See {@link ng.$cacheFactory $cacheFactory}. * */ function $TemplateCacheProvider() { this.$get = ['$cacheFactory', function($cacheFactory) { return $cacheFactory('templates'); }]; } /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! * * DOM-related variables: * * - "node" - DOM Node * - "element" - DOM Element or Node * - "$node" or "$element" - jqLite-wrapped node or element * * * Compiler related stuff: * * - "linkFn" - linking fn of a single directive * - "nodeLinkFn" - function that aggregates all linking fns for a particular node * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) */ var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: '; /** * @ngdoc function * @name ng.$compile * @function * * @description * Compiles a piece of HTML string or DOM into a template and produces a template function, which * can then be used to link {@link ng.$rootScope.Scope scope} and the template together. * * The compilation is a process of walking the DOM tree and trying to match DOM elements to * {@link ng.$compileProvider#directive directives}. For each match it * executes corresponding template function and collects the * instance functions into a single template function which is then returned. * * The template function can then be used once to produce the view or as it is the case with * {@link ng.directive:ngRepeat repeater} many-times, in which * case each call results in a view that is a DOM clone of the original template. * <doc:example module="compile"> <doc:source> <script> // declare a new module, and inject the $compileProvider angular.module('compile', [], function($compileProvider) { // configure new 'compile' directive by passing a directive // factory function. The factory function injects the '$compile' $compileProvider.directive('compile', function($compile) { // directive factory creates a link function return function(scope, element, attrs) { scope.$watch( function(scope) { // watch the 'compile' expression for changes return scope.$eval(attrs.compile); }, function(value) { // when the 'compile' expression changes // assign it into the current DOM element.html(value); // compile the new DOM and link it to the current // scope. // NOTE: we only compile .childNodes so that // we don't get into infinite loop compiling ourselves $compile(element.contents())(scope); } ); }; }) }); function Ctrl($scope) { $scope.name = 'Angular'; $scope.html = 'Hello {{name}}'; } </script> <div ng-controller="Ctrl"> <input ng-model="name"> <br> <textarea ng-model="html"></textarea> <br> <div compile="html"></div> </div> </doc:source> <doc:scenario> it('should auto compile', function() { expect(element('div[compile]').text()).toBe('Hello Angular'); input('html').enter('{{name}}!'); expect(element('div[compile]').text()).toBe('Angular!'); }); </doc:scenario> </doc:example> * * * @param {string|DOMElement} element Element or HTML string to compile into a template function. * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives. * @param {number} maxPriority only apply directives lower then given priority (Only effects the * root element(s), not their children) * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is * called as: <br> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * Calling the linking function returns the element of the template. It is either the original element * passed in, or the clone of the element if the `cloneAttachFn` is provided. * * After linking the view is not updated until after a call to $digest which typically is done by * Angular automatically. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * <pre> * var element = $compile('<p>{{total}}</p>')(scope); * </pre> * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * <pre> * var templateHTML = angular.element('<p>{{total}}</p>'), * scope = ....; * * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) { * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clone` * </pre> * * * For information on how the compiler works, see the * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. */ /** * @ngdoc service * @name ng.$compileProvider * @function * * @description */ $CompileProvider.$inject = ['$provide']; function $CompileProvider($provide) { var hasDirectives = {}, Suffix = 'Directive', COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/, MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ', urlSanitizationWhitelist = /^\s*(https?|ftp|mailto|file):/; /** * @ngdoc function * @name ng.$compileProvider#directive * @methodOf ng.$compileProvider * @function * * @description * Register a new directives with the compiler. * * @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as * <code>ng-bind</code>). * @param {function} directiveFactory An injectable directive factory function. See {@link guide/directive} for more * info. * @returns {ng.$compileProvider} Self for chaining. */ this.directive = function registerDirective(name, directiveFactory) { if (isString(name)) { assertArg(directiveFactory, 'directive'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', function($injector, $exceptionHandler) { var directives = []; forEach(hasDirectives[name], function(directiveFactory) { try { var directive = $injector.invoke(directiveFactory); if (isFunction(directive)) { directive = { compile: valueFn(directive) }; } else if (!directive.compile && directive.link) { directive.compile = valueFn(directive.link); } directive.priority = directive.priority || 0; directive.name = directive.name || name; directive.require = directive.require || (directive.controller && directive.name); directive.restrict = directive.restrict || 'A'; directives.push(directive); } catch (e) { $exceptionHandler(e); } }); return directives; }]); } hasDirectives[name].push(directiveFactory); } else { forEach(name, reverseParams(registerDirective)); } return this; }; /** * @ngdoc function * @name ng.$compileProvider#urlSanitizationWhitelist * @methodOf ng.$compileProvider * @function * * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during a[href] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to a[href] via data-binding is first normalized and turned into an * absolute url. Afterwards the url is matched against the `urlSanitizationWhitelist` regular * expression. If a match is found the original url is written into the dom. Otherwise the * absolute url is prefixed with `'unsafe:'` string and only then it is written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.urlSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { urlSanitizationWhitelist = regexp; return this; } return urlSanitizationWhitelist; }; this.$get = [ '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', '$controller', '$rootScope', '$document', function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, $controller, $rootScope, $document) { var Attributes = function(element, attr) { this.$$element = element; this.$attr = attr || {}; }; Attributes.prototype = { $normalize: directiveNormalize, /** * Set a normalized attribute on the element in a way such that all directives * can share the attribute. This function properly handles boolean attributes. * @param {string} key Normalized key. (ie ngAttribute) * @param {string|boolean} value The value to set. If `null` attribute will be deleted. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. * Defaults to true. * @param {string=} attrName Optional none normalized name. Defaults to key. */ $set: function(key, value, writeAttr, attrName) { var booleanKey = getBooleanAttrName(this.$$element[0], key), $$observers = this.$$observers, normalizedVal; if (booleanKey) { this.$$element.prop(key, value); attrName = booleanKey; } this[key] = value; // translate normalized key to actual key if (attrName) { this.$attr[key] = attrName; } else { attrName = this.$attr[key]; if (!attrName) { this.$attr[key] = attrName = snake_case(key, '-'); } } // sanitize a[href] values if (nodeName_(this.$$element[0]) === 'A' && key === 'href') { urlSanitizationNode.setAttribute('href', value); // href property always returns normalized absolute url, so we can match against that normalizedVal = urlSanitizationNode.href; if (!normalizedVal.match(urlSanitizationWhitelist)) { this[key] = value = 'unsafe:' + normalizedVal; } } if (writeAttr !== false) { if (value === null || value === undefined) { this.$$element.removeAttr(attrName); } else { this.$$element.attr(attrName, value); } } // fire observers $$observers && forEach($$observers[key], function(fn) { try { fn(value); } catch (e) { $exceptionHandler(e); } }); }, /** * Observe an interpolated attribute. * The observer will never be called, if given attribute is not interpolated. * * @param {string} key Normalized key. (ie ngAttribute) . * @param {function(*)} fn Function that will be called whenever the attribute value changes. * @returns {function(*)} the `fn` Function passed in. */ $observe: function(key, fn) { var attrs = this, $$observers = (attrs.$$observers || (attrs.$$observers = {})), listeners = ($$observers[key] || ($$observers[key] = [])); listeners.push(fn); $rootScope.$evalAsync(function() { if (!listeners.$$inter) { // no one registered attribute interpolation function, so lets call it manually fn(attrs[key]); } }); return fn; } }; var urlSanitizationNode = $document[0].createElement('a'), startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') ? identity : function denormalizeTemplate(template) { return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); }, NG_ATTR_BINDING = /^ngAttr[A-Z]/; return compile; //================================ function compile($compileNodes, transcludeFn, maxPriority) { if (!($compileNodes instanceof jqLite)) { // jquery always rewraps, whereas we need to preserve the original selector so that we can modify it. $compileNodes = jqLite($compileNodes); } // We can not compile top level text elements since text nodes can be merged and we will // not be able to attach scope data to them, so we will wrap them in <span> forEach($compileNodes, function(node, index){ if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) { $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0]; } }); var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority); return function publicLinkFn(scope, cloneConnectFn){ assertArg(scope, 'scope'); // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. var $linkNode = cloneConnectFn ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!! : $compileNodes; // Attach scope only to non-text nodes. for(var i = 0, ii = $linkNode.length; i<ii; i++) { var node = $linkNode[i]; if (node.nodeType == 1 /* element */ || node.nodeType == 9 /* document */) { $linkNode.eq(i).data('$scope', scope); } } safeAddClass($linkNode, 'ng-scope'); if (cloneConnectFn) cloneConnectFn($linkNode, scope); if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode); return $linkNode; }; } function wrongMode(localName, mode) { throw Error("Unsupported '" + mode + "' for '" + localName + "'."); } function safeAddClass($element, className) { try { $element.addClass(className); } catch(e) { // ignore, since it means that we are trying to set class on // SVG element, where class name is read-only. } } /** * Compile function matches each node in nodeList against the directives. Once all directives * for a particular node are collected their compile functions are executed. The compile * functions return values - the linking functions - are combined into a composite linking * function, which is the a linking function for the node. * * @param {NodeList} nodeList an array of nodes or NodeList to compile * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the * rootElement must be set the jqLite collection of the compile root. This is * needed so that the jqLite collection items can be replaced with widgets. * @param {number=} max directive priority * @returns {?function} A composite linking function of all of the matched directives or null. */ function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) { var linkFns = [], nodeLinkFn, childLinkFn, directives, attrs, linkFnFound; for(var i = 0; i < nodeList.length; i++) { attrs = new Attributes(); // we must always refer to nodeList[i] since the nodes can be replaced underneath us. directives = collectDirectives(nodeList[i], [], attrs, maxPriority); nodeLinkFn = (directives.length) ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement) : null; childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || !nodeList[i].childNodes || !nodeList[i].childNodes.length) ? null : compileNodes(nodeList[i].childNodes, nodeLinkFn ? nodeLinkFn.transclude : transcludeFn); linkFns.push(nodeLinkFn); linkFns.push(childLinkFn); linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn); } // return a linking function if we have found anything, null otherwise return linkFnFound ? compositeLinkFn : null; function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) { var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn, i, ii, n; // copy nodeList so that linking doesn't break due to live list updates. var stableNodeList = []; for (i = 0, ii = nodeList.length; i < ii; i++) { stableNodeList.push(nodeList[i]); } for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) { node = stableNodeList[n]; nodeLinkFn = linkFns[i++]; childLinkFn = linkFns[i++]; if (nodeLinkFn) { if (nodeLinkFn.scope) { childScope = scope.$new(isObject(nodeLinkFn.scope)); jqLite(node).data('$scope', childScope); } else { childScope = scope; } childTranscludeFn = nodeLinkFn.transclude; if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) { nodeLinkFn(childLinkFn, childScope, node, $rootElement, (function(transcludeFn) { return function(cloneFn) { var transcludeScope = scope.$new(); transcludeScope.$$transcluded = true; return transcludeFn(transcludeScope, cloneFn). bind('$destroy', bind(transcludeScope, transcludeScope.$destroy)); }; })(childTranscludeFn || transcludeFn) ); } else { nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn); } } else if (childLinkFn) { childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn); } } } } /** * Looks for directives on the given node and adds them to the directive collection which is * sorted. * * @param node Node to search. * @param directives An array to which the directives are added to. This array is sorted before * the function returns. * @param attrs The shared attrs object which is used to populate the normalized attributes. * @param {number=} maxPriority Max directive priority. */ function collectDirectives(node, directives, attrs, maxPriority) { var nodeType = node.nodeType, attrsMap = attrs.$attr, match, className; switch(nodeType) { case 1: /* Element */ // use the node name: <directive> addDirective(directives, directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority); // iterate over the attributes for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { attr = nAttrs[j]; if (attr.specified) { name = attr.name; // support ngAttr attribute binding ngAttrName = directiveNormalize(name); if (NG_ATTR_BINDING.test(ngAttrName)) { name = ngAttrName.substr(6).toLowerCase(); } nName = directiveNormalize(name.toLowerCase()); attrsMap[nName] = name; attrs[nName] = value = trim((msie && name == 'href') ? decodeURIComponent(node.getAttribute(name, 2)) : attr.value); if (getBooleanAttrName(node, nName)) { attrs[nName] = true; // presence means true } addAttrInterpolateDirective(node, directives, value, nName); addDirective(directives, nName, 'A', maxPriority); } } // use class as directive className = node.className; if (isString(className) && className !== '') { while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { nName = directiveNormalize(match[2]); if (addDirective(directives, nName, 'C', maxPriority)) { attrs[nName] = trim(match[3]); } className = className.substr(match.index + match[0].length); } } break; case 3: /* Text Node */ addTextInterpolateDirective(directives, node.nodeValue); break; case 8: /* Comment */ try { match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); if (match) { nName = directiveNormalize(match[1]); if (addDirective(directives, nName, 'M', maxPriority)) { attrs[nName] = trim(match[2]); } } } catch (e) { // turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value. // Just ignore it and continue. (Can't seem to reproduce in test case.) } break; } directives.sort(byPriority); return directives; } /** * Once the directives have been collected, their compile functions are executed. This method * is responsible for inlining directive templates as well as terminating the application * of the directives if the terminal directive has been reached. * * @param {Array} directives Array of collected directives to execute their compile function. * this needs to be pre-sorted by priority order. * @param {Node} compileNode The raw DOM node to apply the compile functions to * @param {Object} templateAttrs The shared attribute function * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this * argument has the root jqLite array so that we can replace nodes on it. * @returns linkFn */ function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection) { var terminalPriority = -Number.MAX_VALUE, preLinkFns = [], postLinkFns = [], newScopeDirective = null, newIsolateScopeDirective = null, templateDirective = null, $compileNode = templateAttrs.$$element = jqLite(compileNode), directive, directiveName, $template, transcludeDirective, childTranscludeFn = transcludeFn, controllerDirectives, linkFn, directiveValue; // executes all directives on the current element for(var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; $template = undefined; if (terminalPriority > directive.priority) { break; // prevent further processing of directives } if (directiveValue = directive.scope) { assertNoDuplicate('isolated scope', newIsolateScopeDirective, directive, $compileNode); if (isObject(directiveValue)) { safeAddClass($compileNode, 'ng-isolate-scope'); newIsolateScopeDirective = directive; } safeAddClass($compileNode, 'ng-scope'); newScopeDirective = newScopeDirective || directive; } directiveName = directive.name; if (directiveValue = directive.controller) { controllerDirectives = controllerDirectives || {}; assertNoDuplicate("'" + directiveName + "' controller", controllerDirectives[directiveName], directive, $compileNode); controllerDirectives[directiveName] = directive; } if (directiveValue = directive.transclude) { assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode); transcludeDirective = directive; terminalPriority = directive.priority; if (directiveValue == 'element') { $template = jqLite(compileNode); $compileNode = templateAttrs.$$element = jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' ')); compileNode = $compileNode[0]; replaceWith(jqCollection, jqLite($template[0]), compileNode); childTranscludeFn = compile($template, transcludeFn, terminalPriority); } else { $template = jqLite(JQLiteClone(compileNode)).contents(); $compileNode.html(''); // clear contents childTranscludeFn = compile($template, transcludeFn); } } if (directive.template) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; directiveValue = (isFunction(directive.template)) ? directive.template($compileNode, templateAttrs) : directive.template; directiveValue = denormalizeTemplate(directiveValue); if (directive.replace) { $template = jqLite('<div>' + trim(directiveValue) + '</div>').contents(); compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue); } replaceWith(jqCollection, $compileNode, compileNode); var newTemplateAttrs = {$attr: {}}; // combine directives from the original node and from the template: // - take the array of directives for this element // - split it into two parts, those that were already applied and those that weren't // - collect directives from the template, add them to the second group and sort them // - append the second group with new directives to the first group directives = directives.concat( collectDirectives( compileNode, directives.splice(i + 1, directives.length - (i + 1)), newTemplateAttrs ) ); mergeTemplateAttributes(templateAttrs, newTemplateAttrs); ii = directives.length; } else { $compileNode.html(directiveValue); } } if (directive.templateUrl) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), nodeLinkFn, $compileNode, templateAttrs, jqCollection, directive.replace, childTranscludeFn); ii = directives.length; } else if (directive.compile) { try { linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); if (isFunction(linkFn)) { addLinkFns(null, linkFn); } else if (linkFn) { addLinkFns(linkFn.pre, linkFn.post); } } catch (e) { $exceptionHandler(e, startingTag($compileNode)); } } if (directive.terminal) { nodeLinkFn.terminal = true; terminalPriority = Math.max(terminalPriority, directive.priority); } } nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope; nodeLinkFn.transclude = transcludeDirective && childTranscludeFn; // might be normal or delayed nodeLinkFn depending on if templateUrl is present return nodeLinkFn; //////////////////// function addLinkFns(pre, post) { if (pre) { pre.require = directive.require; preLinkFns.push(pre); } if (post) { post.require = directive.require; postLinkFns.push(post); } } function getControllers(require, $element) { var value, retrievalMethod = 'data', optional = false; if (isString(require)) { while((value = require.charAt(0)) == '^' || value == '?') { require = require.substr(1); if (value == '^') { retrievalMethod = 'inheritedData'; } optional = optional || value == '?'; } value = $element[retrievalMethod]('$' + require + 'Controller'); if (!value && !optional) { throw Error("No controller: " + require); } return value; } else if (isArray(require)) { value = []; forEach(require, function(require) { value.push(getControllers(require, $element)); }); } return value; } function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { var attrs, $element, i, ii, linkFn, controller; if (compileNode === linkNode) { attrs = templateAttrs; } else { attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); } $element = attrs.$$element; if (newIsolateScopeDirective) { var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; var parentScope = scope.$parent || scope; forEach(newIsolateScopeDirective.scope, function(definiton, scopeName) { var match = definiton.match(LOCAL_REGEXP) || [], attrName = match[3] || scopeName, optional = (match[2] == '?'), mode = match[1], // @, =, or & lastValue, parentGet, parentSet; scope.$$isolateBindings[scopeName] = mode + attrName; switch (mode) { case '@': { attrs.$observe(attrName, function(value) { scope[scopeName] = value; }); attrs.$$observers[attrName].$$scope = parentScope; if( attrs[attrName] ) { // If the attribute has been provided then we trigger an interpolation to ensure the value is there for use in the link fn scope[scopeName] = $interpolate(attrs[attrName])(parentScope); } break; } case '=': { if (optional && !attrs[attrName]) { return; } parentGet = $parse(attrs[attrName]); parentSet = parentGet.assign || function() { // reset the change, or we will throw this exception on every $digest lastValue = scope[scopeName] = parentGet(parentScope); throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] + ' (directive: ' + newIsolateScopeDirective.name + ')'); }; lastValue = scope[scopeName] = parentGet(parentScope); scope.$watch(function parentValueWatch() { var parentValue = parentGet(parentScope); if (parentValue !== scope[scopeName]) { // we are out of sync and need to copy if (parentValue !== lastValue) { // parent changed and it has precedence lastValue = scope[scopeName] = parentValue; } else { // if the parent can be assigned then do so parentSet(parentScope, parentValue = lastValue = scope[scopeName]); } } return parentValue; }); break; } case '&': { parentGet = $parse(attrs[attrName]); scope[scopeName] = function(locals) { return parentGet(parentScope, locals); }; break; } default: { throw Error('Invalid isolate scope definition for directive ' + newIsolateScopeDirective.name + ': ' + definiton); } } }); } if (controllerDirectives) { forEach(controllerDirectives, function(directive) { var locals = { $scope: scope, $element: $element, $attrs: attrs, $transclude: boundTranscludeFn }; controller = directive.controller; if (controller == '@') { controller = attrs[directive.name]; } $element.data( '$' + directive.name + 'Controller', $controller(controller, locals)); }); } // PRELINKING for(i = 0, ii = preLinkFns.length; i < ii; i++) { try { linkFn = preLinkFns[i]; linkFn(scope, $element, attrs, linkFn.require && getControllers(linkFn.require, $element)); } catch (e) { $exceptionHandler(e, startingTag($element)); } } // RECURSION childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn); // POSTLINKING for(i = 0, ii = postLinkFns.length; i < ii; i++) { try { linkFn = postLinkFns[i]; linkFn(scope, $element, attrs, linkFn.require && getControllers(linkFn.require, $element)); } catch (e) { $exceptionHandler(e, startingTag($element)); } } } } /** * looks up the directive and decorates it with exception handling and proper parameters. We * call this the boundDirective. * * @param {string} name name of the directive to look up. * @param {string} location The directive must be found in specific format. * String containing any of theses characters: * * * `E`: element name * * `A': attribute * * `C`: class * * `M`: comment * @returns true if directive was added. */ function addDirective(tDirectives, name, location, maxPriority) { var match = false; if (hasDirectives.hasOwnProperty(name)) { for(var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i<ii; i++) { try { directive = directives[i]; if ( (maxPriority === undefined || maxPriority > directive.priority) && directive.restrict.indexOf(location) != -1) { tDirectives.push(directive); match = true; } } catch(e) { $exceptionHandler(e); } } } return match; } /** * When the element is replaced with HTML template then the new attributes * on the template need to be merged with the existing attributes in the DOM. * The desired effect is to have both of the attributes present. * * @param {object} dst destination attributes (original DOM) * @param {object} src source attributes (from the directive template) */ function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr, $element = dst.$$element; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { if (src[key]) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { if (key == 'class') { safeAddClass($element, value); dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; } else if (key == 'style') { $element.attr('style', $element.attr('style') + ';' + value); } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; } }); } function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs, $rootElement, replace, childTranscludeFn) { var linkQueue = [], afterTemplateNodeLinkFn, afterTemplateChildLinkFn, beforeTemplateCompileNode = $compileNode[0], origAsyncDirective = directives.shift(), // The fact that we have to copy and patch the directive seems wrong! derivedSyncDirective = extend({}, origAsyncDirective, { controller: null, templateUrl: null, transclude: null, scope: null }), templateUrl = (isFunction(origAsyncDirective.templateUrl)) ? origAsyncDirective.templateUrl($compileNode, tAttrs) : origAsyncDirective.templateUrl; $compileNode.html(''); $http.get(templateUrl, {cache: $templateCache}). success(function(content) { var compileNode, tempTemplateAttrs, $template; content = denormalizeTemplate(content); if (replace) { $template = jqLite('<div>' + trim(content) + '</div>').contents(); compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content); } tempTemplateAttrs = {$attr: {}}; replaceWith($rootElement, $compileNode, compileNode); collectDirectives(compileNode, directives, tempTemplateAttrs); mergeTemplateAttributes(tAttrs, tempTemplateAttrs); } else { compileNode = beforeTemplateCompileNode; $compileNode.html(content); } directives.unshift(derivedSyncDirective); afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn); afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); while(linkQueue.length) { var scope = linkQueue.shift(), beforeTemplateLinkNode = linkQueue.shift(), linkRootElement = linkQueue.shift(), controller = linkQueue.shift(), linkNode = compileNode; if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { // it was cloned therefore we have to clone as well. linkNode = JQLiteClone(compileNode); replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); } afterTemplateNodeLinkFn(function() { beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller); }, scope, linkNode, $rootElement, controller); } linkQueue = null; }). error(function(response, code, headers, config) { throw Error('Failed to load template: ' + config.url); }); return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) { if (linkQueue) { linkQueue.push(scope); linkQueue.push(node); linkQueue.push(rootElement); linkQueue.push(controller); } else { afterTemplateNodeLinkFn(function() { beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller); }, scope, node, rootElement, controller); } }; } /** * Sorting function for bound directives. */ function byPriority(a, b) { return b.priority - a.priority; } function assertNoDuplicate(what, previousDirective, directive, element) { if (previousDirective) { throw Error('Multiple directives [' + previousDirective.name + ', ' + directive.name + '] asking for ' + what + ' on: ' + startingTag(element)); } } function addTextInterpolateDirective(directives, text) { var interpolateFn = $interpolate(text, true); if (interpolateFn) { directives.push({ priority: 0, compile: valueFn(function textInterpolateLinkFn(scope, node) { var parent = node.parent(), bindings = parent.data('$binding') || []; bindings.push(interpolateFn); safeAddClass(parent.data('$binding', bindings), 'ng-binding'); scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { node[0].nodeValue = value; }); }) }); } } function addAttrInterpolateDirective(node, directives, value, name) { var interpolateFn = $interpolate(value, true); // no interpolation found -> ignore if (!interpolateFn) return; directives.push({ priority: 100, compile: valueFn(function attrInterpolateLinkFn(scope, element, attr) { var $$observers = (attr.$$observers || (attr.$$observers = {})); // we need to interpolate again, in case the attribute value has been updated // (e.g. by another directive's compile function) interpolateFn = $interpolate(attr[name], true); // if attribute was updated so that there is no interpolation going on we don't want to // register any observers if (!interpolateFn) return; attr[name] = interpolateFn(scope); ($$observers[name] || ($$observers[name] = [])).$$inter = true; (attr.$$observers && attr.$$observers[name].$$scope || scope). $watch(interpolateFn, function interpolateFnWatchAction(value) { attr.$set(name, value); }); }) }); } /** * This is a special jqLite.replaceWith, which can replace items which * have no parents, provided that the containing jqLite collection is provided. * * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes * in the root of the tree. * @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell, * but replace its DOM node reference. * @param {Node} newNode The new DOM node. */ function replaceWith($rootElement, $element, newNode) { var oldNode = $element[0], parent = oldNode.parentNode, i, ii; if ($rootElement) { for(i = 0, ii = $rootElement.length; i < ii; i++) { if ($rootElement[i] == oldNode) { $rootElement[i] = newNode; break; } } } if (parent) { parent.replaceChild(newNode, oldNode); } newNode[jqLite.expando] = oldNode[jqLite.expando]; $element[0] = newNode; } }]; } var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; /** * Converts all accepted directives format into proper directive name. * All of these will become 'myDirective': * my:DiRective * my-directive * x-my-directive * data-my:directive * * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function directiveNormalize(name) { return camelCase(name.replace(PREFIX_REGEXP, '')); } /** * @ngdoc object * @name ng.$compile.directive.Attributes * @description * * A shared object between directive compile / linking functions which contains normalized DOM element * attributes. The the values reflect current binding state `{{ }}`. The normalization is needed * since all of these are treated as equivalent in Angular: * * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a"> */ /** * @ngdoc property * @name ng.$compile.directive.Attributes#$attr * @propertyOf ng.$compile.directive.Attributes * @returns {object} A map of DOM element attribute names to the normalized name. This is * needed to do reverse lookup from normalized name back to actual name. */ /** * @ngdoc function * @name ng.$compile.directive.Attributes#$set * @methodOf ng.$compile.directive.Attributes * @function * * @description * Set DOM element attribute value. * * * @param {string} name Normalized element attribute name of the property to modify. The name is * revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr} * property to the original name. * @param {string} value Value to set the attribute to. The value can be an interpolated string. */ /** * Closure compiler type information */ function nodesetLinkingFn( /* angular.Scope */ scope, /* NodeList */ nodeList, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} function directiveLinkingFn( /* nodesetLinkingFn */ nodesetLinkingFn, /* angular.Scope */ scope, /* Node */ node, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} /** * @ngdoc object * @name ng.$controllerProvider * @description * The {@link ng.$controller $controller service} is used by Angular to create new * controllers. * * This provider allows controller registration via the * {@link ng.$controllerProvider#register register} method. */ function $ControllerProvider() { var controllers = {}, CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; /** * @ngdoc function * @name ng.$controllerProvider#register * @methodOf ng.$controllerProvider * @param {string} name Controller name * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI * annotations in the array notation). */ this.register = function(name, constructor) { if (isObject(name)) { extend(controllers, name) } else { controllers[name] = constructor; } }; this.$get = ['$injector', '$window', function($injector, $window) { /** * @ngdoc function * @name ng.$controller * @requires $injector * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * check `window[constructor]` on the global `window` object * * @param {Object} locals Injection locals for Controller. * @return {Object} Instance of given controller. * * @description * `$controller` service is responsible for instantiating controllers. * * It's just a simple call to {@link AUTO.$injector $injector}, but extracted into * a service, so that one can override this service with {@link https://gist.github.com/1649788 * BC version}. */ return function(expression, locals) { var instance, match, constructor, identifier; if(isString(expression)) { match = expression.match(CNTRL_REG), constructor = match[1], identifier = match[3]; expression = controllers.hasOwnProperty(constructor) ? controllers[constructor] : getter(locals.$scope, constructor, true) || getter($window, constructor, true); assertArgFn(expression, constructor, true); } instance = $injector.instantiate(expression, locals); if (identifier) { if (typeof locals.$scope !== 'object') { throw new Error('Can not export controller as "' + identifier + '". ' + 'No scope object provided!'); } locals.$scope[identifier] = instance; } return instance; }; }]; } /** * @ngdoc object * @name ng.$document * @requires $window * * @description * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` * element. */ function $DocumentProvider(){ this.$get = ['$window', function(window){ return jqLite(window.document); }]; } /** * @ngdoc function * @name ng.$exceptionHandler * @requires $log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. * * @param {Error} exception Exception associated with the error. * @param {string=} cause optional information about the context in which * the error was thrown. * */ function $ExceptionHandlerProvider() { this.$get = ['$log', function($log) { return function(exception, cause) { $log.error.apply($log, arguments); }; }]; } /** * @ngdoc object * @name ng.$interpolateProvider * @function * * @description * * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. */ function $InterpolateProvider() { var startSymbol = '{{'; var endSymbol = '}}'; /** * @ngdoc method * @name ng.$interpolateProvider#startSymbol * @methodOf ng.$interpolateProvider * @description * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. * * @param {string=} value new value to set the starting symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.startSymbol = function(value){ if (value) { startSymbol = value; return this; } else { return startSymbol; } }; /** * @ngdoc method * @name ng.$interpolateProvider#endSymbol * @methodOf ng.$interpolateProvider * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * @param {string=} value new value to set the ending symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.endSymbol = function(value){ if (value) { endSymbol = value; return this; } else { return endSymbol; } }; this.$get = ['$parse', '$exceptionHandler', function($parse, $exceptionHandler) { var startSymbolLength = startSymbol.length, endSymbolLength = endSymbol.length; /** * @ngdoc function * @name ng.$interpolate * @function * * @requires $parse * * @description * * Compiles a string with markup into an interpolation function. This service is used by the * HTML {@link ng.$compile $compile} service for data binding. See * {@link ng.$interpolateProvider $interpolateProvider} for configuring the * interpolation markup. * * <pre> var $interpolate = ...; // injected var exp = $interpolate('Hello {{name}}!'); expect(exp({name:'Angular'}).toEqual('Hello Angular!'); </pre> * * * @param {string} text The text with markup to interpolate. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have * embedded expression in order to return an interpolation function. Strings with no * embedded expression will return null for the interpolation function. * @returns {function(context)} an interpolation function which is used to compute the interpolated * string. The function has these parameters: * * * `context`: an object against which any expressions embedded in the strings are evaluated * against. * */ function $interpolate(text, mustHaveExpression) { var startIndex, endIndex, index = 0, parts = [], length = text.length, hasInterpolation = false, fn, exp, concat = []; while(index < length) { if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { (index != startIndex) && parts.push(text.substring(index, startIndex)); parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); fn.exp = exp; index = endIndex + endSymbolLength; hasInterpolation = true; } else { // we did not find anything, so we have to add the remainder to the parts array (index != length) && parts.push(text.substring(index)); index = length; } } if (!(length = parts.length)) { // we added, nothing, must have been an empty string. parts.push(''); length = 1; } if (!mustHaveExpression || hasInterpolation) { concat.length = length; fn = function(context) { try { for(var i = 0, ii = length, part; i<ii; i++) { if (typeof (part = parts[i]) == 'function') { part = part(context); if (part == null || part == undefined) { part = ''; } else if (typeof part != 'string') { part = toJson(part); } } concat[i] = part; } return concat.join(''); } catch(err) { var newErr = new Error('Error while interpolating: ' + text + '\n' + err.toString()); $exceptionHandler(newErr); } }; fn.exp = text; fn.parts = parts; return fn; } } /** * @ngdoc method * @name ng.$interpolate#startSymbol * @methodOf ng.$interpolate * @description * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`. * * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change * the symbol. * * @returns {string} start symbol. */ $interpolate.startSymbol = function() { return startSymbol; } /** * @ngdoc method * @name ng.$interpolate#endSymbol * @methodOf ng.$interpolate * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change * the symbol. * * @returns {string} start symbol. */ $interpolate.endSymbol = function() { return endSymbol; } return $interpolate; }]; } var SERVER_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; /** * Encode path using encodeUriSegment, ignoring forward slashes * * @param {string} path Path to encode * @returns {string} */ function encodePath(path) { var segments = path.split('/'), i = segments.length; while (i--) { segments[i] = encodeUriSegment(segments[i]); } return segments.join('/'); } function matchUrl(url, obj) { var match = SERVER_MATCH.exec(url); obj.$$protocol = match[1]; obj.$$host = match[3]; obj.$$port = int(match[5]) || DEFAULT_PORTS[match[1]] || null; } function matchAppUrl(url, obj) { var match = PATH_MATCH.exec(url); obj.$$path = decodeURIComponent(match[1]); obj.$$search = parseKeyValue(match[3]); obj.$$hash = decodeURIComponent(match[5] || ''); // make sure path starts with '/'; if (obj.$$path && obj.$$path.charAt(0) != '/') obj.$$path = '/' + obj.$$path; } function composeProtocolHostPort(protocol, host, port) { return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port); } /** * * @param {string} begin * @param {string} whole * @param {string} otherwise * @returns {string} returns text from whole after begin or otherwise if it does not begin with expected string. */ function beginsWith(begin, whole, otherwise) { return whole.indexOf(begin) == 0 ? whole.substr(begin.length) : otherwise; } function stripHash(url) { var index = url.indexOf('#'); return index == -1 ? url : url.substr(0, index); } function stripFile(url) { return url.substr(0, stripHash(url).lastIndexOf('/') + 1); } /* return the server only */ function serverBase(url) { return url.substring(0, url.indexOf('/', url.indexOf('//') + 2)); } /** * LocationHtml5Url represents an url * This object is exposed as $location service when HTML5 mode is enabled and supported * * @constructor * @param {string} appBase application base URL * @param {string} basePrefix url path prefix */ function LocationHtml5Url(appBase, basePrefix) { basePrefix = basePrefix || ''; var appBaseNoFile = stripFile(appBase); /** * Parse given html5 (regular) url string into properties * @param {string} newAbsoluteUrl HTML5 url * @private */ this.$$parse = function(url) { var parsed = {} matchUrl(url, parsed); var pathUrl = beginsWith(appBaseNoFile, url); if (!isString(pathUrl)) { throw Error('Invalid url "' + url + '", missing path prefix "' + appBaseNoFile + '".'); } matchAppUrl(pathUrl, parsed); extend(this, parsed); if (!this.$$path) { this.$$path = '/'; } this.$$compose(); }; /** * Compose url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' }; this.$$rewrite = function(url) { var appUrl, prevAppUrl; if ( (appUrl = beginsWith(appBase, url)) !== undefined ) { prevAppUrl = appUrl; if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) { return appBaseNoFile + (beginsWith('/', appUrl) || appUrl); } else { return appBase + prevAppUrl; } } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) { return appBaseNoFile + appUrl; } else if (appBaseNoFile == url + '/') { return appBaseNoFile; } } } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is disabled or not supported * * @constructor * @param {string} appBase application base URL * @param {string} hashPrefix hashbang prefix */ function LocationHashbangUrl(appBase, hashPrefix) { var appBaseNoFile = stripFile(appBase); /** * Parse given hashbang url into properties * @param {string} url Hashbang url * @private */ this.$$parse = function(url) { matchUrl(url, this); var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url); if (!isString(withoutBaseUrl)) { throw new Error('Invalid url "' + url + '", does not start with "' + appBase + '".'); } var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' ? beginsWith(hashPrefix, withoutBaseUrl) : withoutBaseUrl; if (!isString(withoutHashUrl)) { throw new Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '".'); } matchAppUrl(withoutHashUrl, this); this.$$compose(); }; /** * Compose hashbang url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); }; this.$$rewrite = function(url) { if(stripHash(appBase) == stripHash(url)) { return url; } } } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is enabled but the browser * does not support it. * * @constructor * @param {string} appBase application base URL * @param {string} hashPrefix hashbang prefix */ function LocationHashbangInHtml5Url(appBase, hashPrefix) { LocationHashbangUrl.apply(this, arguments); var appBaseNoFile = stripFile(appBase); this.$$rewrite = function(url) { var appUrl; if ( appBase == stripHash(url) ) { return url; } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) { return appBase + hashPrefix + appUrl; } else if ( appBaseNoFile === url + '/') { return appBaseNoFile; } } } LocationHashbangInHtml5Url.prototype = LocationHashbangUrl.prototype = LocationHtml5Url.prototype = { /** * Has any change been replacing ? * @private */ $$replace: false, /** * @ngdoc method * @name ng.$location#absUrl * @methodOf ng.$location * * @description * This method is getter only. * * Return full url representation with all segments encoded according to rules specified in * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. * * @return {string} full url */ absUrl: locationGetter('$$absUrl'), /** * @ngdoc method * @name ng.$location#url * @methodOf ng.$location * * @description * This method is getter / setter. * * Return url (e.g. `/path?a=b#hash`) when called without any parameter. * * Change path, search and hash, when called with parameter and return `$location`. * * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) * @return {string} url */ url: function(url, replace) { if (isUndefined(url)) return this.$$url; var match = PATH_MATCH.exec(url); if (match[1]) this.path(decodeURIComponent(match[1])); if (match[2] || match[1]) this.search(match[3] || ''); this.hash(match[5] || '', replace); return this; }, /** * @ngdoc method * @name ng.$location#protocol * @methodOf ng.$location * * @description * This method is getter only. * * Return protocol of current url. * * @return {string} protocol of current url */ protocol: locationGetter('$$protocol'), /** * @ngdoc method * @name ng.$location#host * @methodOf ng.$location * * @description * This method is getter only. * * Return host of current url. * * @return {string} host of current url. */ host: locationGetter('$$host'), /** * @ngdoc method * @name ng.$location#port * @methodOf ng.$location * * @description * This method is getter only. * * Return port of current url. * * @return {Number} port */ port: locationGetter('$$port'), /** * @ngdoc method * @name ng.$location#path * @methodOf ng.$location * * @description * This method is getter / setter. * * Return path of current url when called without any parameter. * * Change path when called with parameter and return `$location`. * * Note: Path should always begin with forward slash (/), this method will add the forward slash * if it is missing. * * @param {string=} path New path * @return {string} path */ path: locationGetterSetter('$$path', function(path) { return path.charAt(0) == '/' ? path : '/' + path; }), /** * @ngdoc method * @name ng.$location#search * @methodOf ng.$location * * @description * This method is getter / setter. * * Return search part (as object) of current url when called without any parameter. * * Change search part when called with parameter and return `$location`. * * @param {string|object<string,string>=} search New search params - string or hash object * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a * single search parameter. If the value is `null`, the parameter will be deleted. * * @return {string} search */ search: function(search, paramValue) { if (isUndefined(search)) return this.$$search; if (isDefined(paramValue)) { if (paramValue === null) { delete this.$$search[search]; } else { this.$$search[search] = paramValue; } } else { this.$$search = isString(search) ? parseKeyValue(search) : search; } this.$$compose(); return this; }, /** * @ngdoc method * @name ng.$location#hash * @methodOf ng.$location * * @description * This method is getter / setter. * * Return hash fragment when called without any parameter. * * Change hash fragment when called with parameter and return `$location`. * * @param {string=} hash New hash fragment * @return {string} hash */ hash: locationGetterSetter('$$hash', identity), /** * @ngdoc method * @name ng.$location#replace * @methodOf ng.$location * * @description * If called, all changes to $location during current `$digest` will be replacing current history * record, instead of adding new one. */ replace: function() { this.$$replace = true; return this; } }; function locationGetter(property) { return function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { return function(value) { if (isUndefined(value)) return this[property]; this[property] = preprocess(value); this.$$compose(); return this; }; } /** * @ngdoc object * @name ng.$location * * @requires $browser * @requires $sniffer * @requires $rootElement * * @description * The $location service parses the URL in the browser address bar (based on the * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL * available to your application. Changes to the URL in the address bar are reflected into * $location service and changes to $location are reflected into the browser address bar. * * **The $location service:** * * - Exposes the current URL in the browser address bar, so you can * - Watch and observe the URL. * - Change the URL. * - Synchronizes the URL with the browser when the user * - Changes the address bar. * - Clicks the back or forward button (or clicks a History link). * - Clicks on a link. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). * * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular * Services: Using $location} */ /** * @ngdoc object * @name ng.$locationProvider * @description * Use the `$locationProvider` to configure how the application deep linking paths are stored. */ function $LocationProvider(){ var hashPrefix = '', html5Mode = false; /** * @ngdoc property * @name ng.$locationProvider#hashPrefix * @methodOf ng.$locationProvider * @description * @param {string=} prefix Prefix for hash part (containing path and search) * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.hashPrefix = function(prefix) { if (isDefined(prefix)) { hashPrefix = prefix; return this; } else { return hashPrefix; } }; /** * @ngdoc property * @name ng.$locationProvider#html5Mode * @methodOf ng.$locationProvider * @description * @param {string=} mode Use HTML5 strategy if available. * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.html5Mode = function(mode) { if (isDefined(mode)) { html5Mode = mode; return this; } else { return html5Mode; } }; this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', function( $rootScope, $browser, $sniffer, $rootElement) { var $location, LocationMode, baseHref = $browser.baseHref(), initialUrl = $browser.url(), appBase; if (html5Mode) { appBase = baseHref ? serverBase(initialUrl) + baseHref : initialUrl; LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; } else { appBase = stripHash(initialUrl); LocationMode = LocationHashbangUrl; } $location = new LocationMode(appBase, '#' + hashPrefix); $location.$$parse($location.$$rewrite(initialUrl)); $rootElement.bind('click', function(event) { // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then if (event.ctrlKey || event.metaKey || event.which == 2) return; var elm = jqLite(event.target); // traverse the DOM up to find first A tag while (lowercase(elm[0].nodeName) !== 'a') { // ignore rewriting if no A tag (reached root element, or no parent - removed from document) if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; } var absHref = elm.prop('href'); var rewrittenUrl = $location.$$rewrite(absHref); if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) { event.preventDefault(); if (rewrittenUrl != $browser.url()) { // update location manually $location.$$parse(rewrittenUrl); $rootScope.$apply(); // hack to work around FF6 bug 684208 when scenario runner clicks on links window.angular['ff-684208-preventDefault'] = true; } } }); // rewrite hashbang url <> html5 url if ($location.absUrl() != initialUrl) { $browser.url($location.absUrl(), true); } // update $location when $browser url changes $browser.onUrlChange(function(newUrl) { if ($location.absUrl() != newUrl) { if ($rootScope.$broadcast('$locationChangeStart', newUrl, $location.absUrl()).defaultPrevented) { $browser.url($location.absUrl()); return; } $rootScope.$evalAsync(function() { var oldUrl = $location.absUrl(); $location.$$parse(newUrl); afterLocationChange(oldUrl); }); if (!$rootScope.$$phase) $rootScope.$digest(); } }); // update browser var changeCounter = 0; $rootScope.$watch(function $locationWatch() { var oldUrl = $browser.url(); var currentReplace = $location.$$replace; if (!changeCounter || oldUrl != $location.absUrl()) { changeCounter++; $rootScope.$evalAsync(function() { if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). defaultPrevented) { $location.$$parse(oldUrl); } else { $browser.url($location.absUrl(), currentReplace); afterLocationChange(oldUrl); } }); } $location.$$replace = false; return changeCounter; }); return $location; function afterLocationChange(oldUrl) { $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl); } }]; } /** * @ngdoc object * @name ng.$log * @requires $window * * @description * Simple service for logging. Default implementation writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * @example <example> <file name="script.js"> function LogCtrl($scope, $log) { $scope.$log = $log; $scope.message = 'Hello World!'; } </file> <file name="index.html"> <div ng-controller="LogCtrl"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" ng-model="message"/> <button ng-click="$log.log(message)">log</button> <button ng-click="$log.warn(message)">warn</button> <button ng-click="$log.info(message)">info</button> <button ng-click="$log.error(message)">error</button> </div> </file> </example> */ /** * @ngdoc object * @name ng.$logProvider * @description * Use the `$logProvider` to configure how the application logs messages */ function $LogProvider(){ var debug = true, self = this; /** * @ngdoc property * @name ng.$logProvider#debugEnabled * @methodOf ng.$logProvider * @description * @param {string=} flag enable or disable debug level messages * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.debugEnabled = function(flag) { if (isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = ['$window', function($window){ return { /** * @ngdoc method * @name ng.$log#log * @methodOf ng.$log * * @description * Write a log message */ log: consoleLog('log'), /** * @ngdoc method * @name ng.$log#warn * @methodOf ng.$log * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @ngdoc method * @name ng.$log#info * @methodOf ng.$log * * @description * Write an information message */ info: consoleLog('info'), /** * @ngdoc method * @name ng.$log#error * @methodOf ng.$log * * @description * Write an error message */ error: consoleLog('error'), /** * @ngdoc method * @name ng.$log#debug * @methodOf ng.$log * * @description * Write a debug message */ debug: (function () { var fn = consoleLog('debug'); return function() { if (debug) { fn.apply(self, arguments); } } }()) }; function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } function consoleLog(type) { var console = $window.console || {}, logFn = console[type] || console.log || noop; if (logFn.apply) { return function() { var args = []; forEach(arguments, function(arg) { args.push(formatError(arg)); }); return logFn.apply(console, args); }; } // we are IE which either doesn't have window.console => this is noop and we do nothing, // or we are IE where console.log doesn't have apply so we log at least first 2 args return function(arg1, arg2) { logFn(arg1, arg2); } } }]; } var OPERATORS = { 'null':function(){return null;}, 'true':function(){return true;}, 'false':function(){return false;}, undefined:noop, '+':function(self, locals, a,b){ a=a(self, locals); b=b(self, locals); if (isDefined(a)) { if (isDefined(b)) { return a + b; } return a; } return isDefined(b)?b:undefined;}, '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, '=':noop, '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);}, '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);}, '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);}, '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, // '|':function(self, locals, a,b){return a|b;}, '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, '!':function(self, locals, a){return !a(self, locals);} }; var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; function lex(text, csp){ var tokens = [], token, index = 0, json = [], ch, lastCh = ':'; // can start regexp while (index < text.length) { ch = text.charAt(index); if (is('"\'')) { readString(ch); } else if (isNumber(ch) || is('.') && isNumber(peek())) { readNumber(); } else if (isIdent(ch)) { readIdent(); // identifiers can only be if the preceding char was a { or , if (was('{,') && json[0]=='{' && (token=tokens[tokens.length-1])) { token.json = token.text.indexOf('.') == -1; } } else if (is('(){}[].,;:?')) { tokens.push({ index:index, text:ch, json:(was(':[,') && is('{[')) || is('}]:,') }); if (is('{[')) json.unshift(ch); if (is('}]')) json.shift(); index++; } else if (isWhitespace(ch)) { index++; continue; } else { var ch2 = ch + peek(), ch3 = ch2 + peek(2), fn = OPERATORS[ch], fn2 = OPERATORS[ch2], fn3 = OPERATORS[ch3]; if (fn3) { tokens.push({index:index, text:ch3, fn:fn3}); index += 3; } else if (fn2) { tokens.push({index:index, text:ch2, fn:fn2}); index += 2; } else if (fn) { tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); index += 1; } else { throwError("Unexpected next character ", index, index+1); } } lastCh = ch; } return tokens; function is(chars) { return chars.indexOf(ch) != -1; } function was(chars) { return chars.indexOf(lastCh) != -1; } function peek(i) { var num = i || 1; return index + num < text.length ? text.charAt(index + num) : false; } function isNumber(ch) { return '0' <= ch && ch <= '9'; } function isWhitespace(ch) { return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 } function isIdent(ch) { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' == ch || ch == '$'; } function isExpOperator(ch) { return ch == '-' || ch == '+' || isNumber(ch); } function throwError(error, start, end) { end = end || index; throw Error("Lexer Error: " + error + " at column" + (isDefined(start) ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]" : " " + end) + " in expression [" + text + "]."); } function readNumber() { var number = ""; var start = index; while (index < text.length) { var ch = lowercase(text.charAt(index)); if (ch == '.' || isNumber(ch)) { number += ch; } else { var peekCh = peek(); if (ch == 'e' && isExpOperator(peekCh)) { number += ch; } else if (isExpOperator(ch) && peekCh && isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (isExpOperator(ch) && (!peekCh || !isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { throwError('Invalid exponent'); } else { break; } } index++; } number = 1 * number; tokens.push({index:start, text:number, json:true, fn:function() {return number;}}); } function readIdent() { var ident = "", start = index, lastDot, peekIndex, methodName, ch; while (index < text.length) { ch = text.charAt(index); if (ch == '.' || isIdent(ch) || isNumber(ch)) { if (ch == '.') lastDot = index; ident += ch; } else { break; } index++; } //check if this is not a method invocation and if it is back out to last dot if (lastDot) { peekIndex = index; while(peekIndex < text.length) { ch = text.charAt(peekIndex); if (ch == '(') { methodName = ident.substr(lastDot - start + 1); ident = ident.substr(0, lastDot - start); index = peekIndex; break; } if(isWhitespace(ch)) { peekIndex++; } else { break; } } } var token = { index:start, text:ident }; if (OPERATORS.hasOwnProperty(ident)) { token.fn = token.json = OPERATORS[ident]; } else { var getter = getterFn(ident, csp); token.fn = extend(function(self, locals) { return (getter(self, locals)); }, { assign: function(self, value) { return setter(self, ident, value); } }); } tokens.push(token); if (methodName) { tokens.push({ index:lastDot, text: '.', json: false }); tokens.push({ index: lastDot + 1, text: methodName, json: false }); } } function readString(quote) { var start = index; index++; var string = ""; var rawString = quote; var escape = false; while (index < text.length) { var ch = text.charAt(index); rawString += ch; if (escape) { if (ch == 'u') { var hex = text.substring(index + 1, index + 5); if (!hex.match(/[\da-f]{4}/i)) throwError( "Invalid unicode escape [\\u" + hex + "]"); index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch == '\\') { escape = true; } else if (ch == quote) { index++; tokens.push({ index:start, text:rawString, string:string, json:true, fn:function() { return string; } }); return; } else { string += ch; } index++; } throwError("Unterminated quote", start); } } ///////////////////////////////////////// function parser(text, json, $filter, csp){ var ZERO = valueFn(0), value, tokens = lex(text, csp), assignment = _assignment, functionCall = _functionCall, fieldAccess = _fieldAccess, objectIndex = _objectIndex, filterChain = _filterChain; if(json){ // The extra level of aliasing is here, just in case the lexer misses something, so that // we prevent any accidental execution in JSON. assignment = logicalOR; functionCall = fieldAccess = objectIndex = filterChain = function() { throwError("is not valid json", {text:text, index:0}); }; value = primary(); } else { value = statements(); } if (tokens.length !== 0) { throwError("is an unexpected token", tokens[0]); } value.literal = !!value.literal; value.constant = !!value.constant; return value; /////////////////////////////////// function throwError(msg, token) { throw Error("Syntax Error: Token '" + token.text + "' " + msg + " at column " + (token.index + 1) + " of the expression [" + text + "] starting at [" + text.substring(token.index) + "]."); } function peekToken() { if (tokens.length === 0) throw Error("Unexpected end of expression: " + text); return tokens[0]; } function peek(e1, e2, e3, e4) { if (tokens.length > 0) { var token = tokens[0]; var t = token.text; if (t==e1 || t==e2 || t==e3 || t==e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; } function expect(e1, e2, e3, e4){ var token = peek(e1, e2, e3, e4); if (token) { if (json && !token.json) { throwError("is not valid json", token); } tokens.shift(); return token; } return false; } function consume(e1){ if (!expect(e1)) { throwError("is unexpected, expecting [" + e1 + "]", peek()); } } function unaryFn(fn, right) { return extend(function(self, locals) { return fn(self, locals, right); }, { constant:right.constant }); } function ternaryFn(left, middle, right){ return extend(function(self, locals){ return left(self, locals) ? middle(self, locals) : right(self, locals); }, { constant: left.constant && middle.constant && right.constant }); } function binaryFn(left, fn, right) { return extend(function(self, locals) { return fn(self, locals, left, right); }, { constant:left.constant && right.constant }); } function statements() { var statements = []; while(true) { if (tokens.length > 0 && !peek('}', ')', ';', ']')) statements.push(filterChain()); if (!expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? return statements.length == 1 ? statements[0] : function(self, locals){ var value; for ( var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) value = statement(self, locals); } return value; }; } } } function _filterChain() { var left = expression(); var token; while(true) { if ((token = expect('|'))) { left = binaryFn(left, token.fn, filter()); } else { return left; } } } function filter() { var token = expect(); var fn = $filter(token.text); var argsFn = []; while(true) { if ((token = expect(':'))) { argsFn.push(expression()); } else { var fnInvoke = function(self, locals, input){ var args = [input]; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } return fn.apply(self, args); }; return function() { return fnInvoke; }; } } } function expression() { return assignment(); } function _assignment() { var left = ternary(); var right; var token; if ((token = expect('='))) { if (!left.assign) { throwError("implies assignment but [" + text.substring(0, token.index) + "] can not be assigned to", token); } right = ternary(); return function(scope, locals){ return left.assign(scope, right(scope, locals), locals); }; } else { return left; } } function ternary() { var left = logicalOR(); var middle; var token; if((token = expect('?'))){ middle = ternary(); if((token = expect(':'))){ return ternaryFn(left, middle, ternary()); } else { throwError('expected :', token); } } else { return left; } } function logicalOR() { var left = logicalAND(); var token; while(true) { if ((token = expect('||'))) { left = binaryFn(left, token.fn, logicalAND()); } else { return left; } } } function logicalAND() { var left = equality(); var token; if ((token = expect('&&'))) { left = binaryFn(left, token.fn, logicalAND()); } return left; } function equality() { var left = relational(); var token; if ((token = expect('==','!=','===','!=='))) { left = binaryFn(left, token.fn, equality()); } return left; } function relational() { var left = additive(); var token; if ((token = expect('<', '>', '<=', '>='))) { left = binaryFn(left, token.fn, relational()); } return left; } function additive() { var left = multiplicative(); var token; while ((token = expect('+','-'))) { left = binaryFn(left, token.fn, multiplicative()); } return left; } function multiplicative() { var left = unary(); var token; while ((token = expect('*','/','%'))) { left = binaryFn(left, token.fn, unary()); } return left; } function unary() { var token; if (expect('+')) { return primary(); } else if ((token = expect('-'))) { return binaryFn(ZERO, token.fn, unary()); } else if ((token = expect('!'))) { return unaryFn(token.fn, unary()); } else { return primary(); } } function primary() { var primary; if (expect('(')) { primary = filterChain(); consume(')'); } else if (expect('[')) { primary = arrayDeclaration(); } else if (expect('{')) { primary = object(); } else { var token = expect(); primary = token.fn; if (!primary) { throwError("not a primary expression", token); } if (token.json) { primary.constant = primary.literal = true; } } var next, context; while ((next = expect('(', '[', '.'))) { if (next.text === '(') { primary = functionCall(primary, context); context = null; } else if (next.text === '[') { context = primary; primary = objectIndex(primary); } else if (next.text === '.') { context = primary; primary = fieldAccess(primary); } else { throwError("IMPOSSIBLE"); } } return primary; } function _fieldAccess(object) { var field = expect().text; var getter = getterFn(field, csp); return extend( function(scope, locals, self) { return getter(self || object(scope, locals), locals); }, { assign:function(scope, value, locals) { return setter(object(scope, locals), field, value); } } ); } function _objectIndex(obj) { var indexFn = expression(); consume(']'); return extend( function(self, locals){ var o = obj(self, locals), i = indexFn(self, locals), v, p; if (!o) return undefined; v = o[i]; if (v && v.then) { p = v; if (!('$$v' in v)) { p.$$v = undefined; p.then(function(val) { p.$$v = val; }); } v = v.$$v; } return v; }, { assign:function(self, value, locals){ return obj(self, locals)[indexFn(self, locals)] = value; } }); } function _functionCall(fn, contextGetter) { var argsFn = []; if (peekToken().text != ')') { do { argsFn.push(expression()); } while (expect(',')); } consume(')'); return function(scope, locals){ var args = [], context = contextGetter ? contextGetter(scope, locals) : scope; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](scope, locals)); } var fnPtr = fn(scope, locals, context) || noop; // IE stupidity! return fnPtr.apply ? fnPtr.apply(context, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); }; } // This is used with json array declaration function arrayDeclaration () { var elementFns = []; var allConstant = true; if (peekToken().text != ']') { do { var elementFn = expression(); elementFns.push(elementFn); if (!elementFn.constant) { allConstant = false; } } while (expect(',')); } consume(']'); return extend(function(self, locals){ var array = []; for ( var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self, locals)); } return array; }, { literal:true, constant:allConstant }); } function object () { var keyValues = []; var allConstant = true; if (peekToken().text != '}') { do { var token = expect(), key = token.string || token.text; consume(":"); var value = expression(); keyValues.push({key:key, value:value}); if (!value.constant) { allConstant = false; } } while (expect(',')); } consume('}'); return extend(function(self, locals){ var object = {}; for ( var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; object[keyValue.key] = keyValue.value(self, locals); } return object; }, { literal:true, constant:allConstant }); } } ////////////////////////////////////////////////// // Parser helper functions ////////////////////////////////////////////////// function setter(obj, path, setValue) { var element = path.split('.'); for (var i = 0; element.length > 1; i++) { var key = element.shift(); var propertyObj = obj[key]; if (!propertyObj) { propertyObj = {}; obj[key] = propertyObj; } obj = propertyObj; } obj[element.shift()] = setValue; return setValue; } /** * Return the value accessible from the object by path. Any undefined traversals are ignored * @param {Object} obj starting object * @param {string} path path to traverse * @param {boolean=true} bindFnToScope * @returns value as accessible by path */ //TODO(misko): this function needs to be removed function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; } var getterFnCache = {}; /** * Implementation of the "Black Hole" variant from: * - http://jsperf.com/angularjs-parse-getter/4 * - http://jsperf.com/path-evaluation-simplified/7 */ function cspSafeGetterFn(key0, key1, key2, key3, key4) { return function(scope, locals) { var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, promise; if (pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key0]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key1 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key1]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key2 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key2]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key3 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key3]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key4 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key4]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } return pathVal; }; } function getterFn(path, csp) { if (getterFnCache.hasOwnProperty(path)) { return getterFnCache[path]; } var pathKeys = path.split('.'), pathKeysLength = pathKeys.length, fn; if (csp) { fn = (pathKeysLength < 6) ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4]) : function(scope, locals) { var i = 0, val; do { val = cspSafeGetterFn( pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++] )(scope, locals); locals = undefined; // clear after first iteration scope = val; } while (i < pathKeysLength); return val; } } else { var code = 'var l, fn, p;\n'; forEach(pathKeys, function(key, index) { code += 'if(s === null || s === undefined) return s;\n' + 'l=s;\n' + 's='+ (index // we simply dereference 's' on any .dot notation ? 's' // but if we are first then we check locals first, and if so read it first : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + 'if (s && s.then) {\n' + ' if (!("$$v" in s)) {\n' + ' p=s;\n' + ' p.$$v = undefined;\n' + ' p.then(function(v) {p.$$v=v;});\n' + '}\n' + ' s=s.$$v\n' + '}\n'; }); code += 'return s;'; fn = Function('s', 'k', code); // s=scope, k=locals fn.toString = function() { return code; }; } return getterFnCache[path] = fn; } /////////////////////////////////// /** * @ngdoc function * @name ng.$parse * @function * * @description * * Converts Angular {@link guide/expression expression} into a function. * * <pre> * var getter = $parse('user.name'); * var setter = getter.assign; * var context = {user:{name:'angular'}}; * var locals = {user:{name:'local'}}; * * expect(getter(context)).toEqual('angular'); * setter(context, 'newValue'); * expect(context.user.name).toEqual('newValue'); * expect(getter(context, locals)).toEqual('local'); * </pre> * * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. * * The returned function also has the following properties: * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript * literal. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript * constant literals. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be * set to a function to change its value on the given context. * */ function $ParseProvider() { var cache = {}; this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { return function(exp) { switch(typeof exp) { case 'string': return cache.hasOwnProperty(exp) ? cache[exp] : cache[exp] = parser(exp, false, $filter, $sniffer.csp); case 'function': return exp; default: return noop; } }; }]; } /** * @ngdoc service * @name ng.$q * @requires $rootScope * * @description * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). * * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an * interface for interacting with an object that represents the result of an action that is * performed asynchronously, and may or may not be finished at any given point in time. * * From the perspective of dealing with error handling, deferred and promise APIs are to * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. * * <pre> * // for the purpose of this example let's assume that variables `$q` and `scope` are * // available in the current lexical scope (they could have been injected or passed in). * * function asyncGreet(name) { * var deferred = $q.defer(); * * setTimeout(function() { * // since this fn executes async in a future turn of the event loop, we need to wrap * // our code into an $apply call so that the model changes are properly observed. * scope.$apply(function() { * if (okToGreet(name)) { * deferred.resolve('Hello, ' + name + '!'); * } else { * deferred.reject('Greeting ' + name + ' is not allowed.'); * } * }); * }, 1000); * * return deferred.promise; * } * * var promise = asyncGreet('Robin Hood'); * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * }); * </pre> * * At first it might not be obvious why this extra complexity is worth the trouble. The payoff * comes in the way of * [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md). * * Additionally the promise api allows for composition that is very hard to do with the * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the * section on serial or parallel joining of promises. * * * # The Deferred API * * A new instance of deferred is constructed by calling `$q.defer()`. * * The purpose of the deferred object is to expose the associated Promise instance as well as APIs * that can be used for signaling the successful or unsuccessful completion of the task. * * **Methods** * * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection * constructed via `$q.reject`, the promise will be rejected instead. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to * resolving it with a rejection constructed via `$q.reject`. * * **Properties** * * - promise – `{Promise}` – promise object associated with this deferred. * * * # The Promise API * * A new promise instance is created when a deferred instance is created and can be retrieved by * calling `deferred.promise`. * * The purpose of the promise object is to allow for interested parties to get access to the result * of the deferred task when it completes. * * **Methods** * * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved * or rejected calls one of the success or error callbacks asynchronously as soon as the result * is available. The callbacks are called with a single argument the result or rejection reason. * * This method *returns a new promise* which is resolved or rejected via the return value of the * `successCallback` or `errorCallback`. * * - `always(callback)` – allows you to observe either the fulfillment or rejection of a promise, * but to do so without modifying the final value. This is useful to release resources or do some * clean-up that needs to be done whether the promise was rejected or resolved. See the [full * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for * more information. * * # Chaining promises * * Because calling `then` api of a promise returns a new derived promise, it is easily possible * to create a chain of promises: * * <pre> * promiseB = promiseA.then(function(result) { * return result + 1; * }); * * // promiseB will be resolved immediately after promiseA is resolved and its value will be * // the result of promiseA incremented by 1 * </pre> * * It is possible to create chains of any length and since a promise can be resolved with another * promise (which will defer its resolution further), it is possible to pause/defer resolution of * the promises at any point in the chain. This makes it possible to implement powerful apis like * $http's response interceptors. * * * # Differences between Kris Kowal's Q and $q * * There are three main differences: * * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation * mechanism in angular, which means faster propagation of resolution or rejection into your * models and avoiding unnecessary browser repaints, which would result in flickering UI. * - $q promises are recognized by the templating engine in angular, which means that in templates * you can treat promises attached to a scope as if they were the resulting values. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains * all the important functionality needed for common async tasks. * * # Testing * * <pre> * it('should simulate promise', inject(function($q, $rootScope) { * var deferred = $q.defer(); * var promise = deferred.promise; * var resolvedValue; * * promise.then(function(value) { resolvedValue = value; }); * expect(resolvedValue).toBeUndefined(); * * // Simulate resolving of promise * deferred.resolve(123); * // Note that the 'then' function does not get called synchronously. * // This is because we want the promise API to always be async, whether or not * // it got called synchronously or asynchronously. * expect(resolvedValue).toBeUndefined(); * * // Propagate promise resolution to 'then' functions using $apply(). * $rootScope.$apply(); * expect(resolvedValue).toEqual(123); * }); * </pre> */ function $QProvider() { this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { return qFactory(function(callback) { $rootScope.$evalAsync(callback); }, $exceptionHandler); }]; } /** * Constructs a promise manager. * * @param {function(function)} nextTick Function for executing functions in the next turn. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for * debugging purposes. * @returns {object} Promise manager. */ function qFactory(nextTick, exceptionHandler) { /** * @ngdoc * @name ng.$q#defer * @methodOf ng.$q * @description * Creates a `Deferred` object which represents a task which will finish in the future. * * @returns {Deferred} Returns a new instance of deferred. */ var defer = function() { var pending = [], value, deferred; deferred = { resolve: function(val) { if (pending) { var callbacks = pending; pending = undefined; value = ref(val); if (callbacks.length) { nextTick(function() { var callback; for (var i = 0, ii = callbacks.length; i < ii; i++) { callback = callbacks[i]; value.then(callback[0], callback[1]); } }); } } }, reject: function(reason) { deferred.resolve(reject(reason)); }, promise: { then: function(callback, errback) { var result = defer(); var wrappedCallback = function(value) { try { result.resolve((callback || defaultCallback)(value)); } catch(e) { exceptionHandler(e); result.reject(e); } }; var wrappedErrback = function(reason) { try { result.resolve((errback || defaultErrback)(reason)); } catch(e) { exceptionHandler(e); result.reject(e); } }; if (pending) { pending.push([wrappedCallback, wrappedErrback]); } else { value.then(wrappedCallback, wrappedErrback); } return result.promise; }, always: function(callback) { function makePromise(value, resolved) { var result = defer(); if (resolved) { result.resolve(value); } else { result.reject(value); } return result.promise; } function handleCallback(value, isResolved) { var callbackOutput = null; try { callbackOutput = (callback ||defaultCallback)(); } catch(e) { return makePromise(e, false); } if (callbackOutput && callbackOutput.then) { return callbackOutput.then(function() { return makePromise(value, isResolved); }, function(error) { return makePromise(error, false); }); } else { return makePromise(value, isResolved); } } return this.then(function(value) { return handleCallback(value, true); }, function(error) { return handleCallback(error, false); }); } } }; return deferred; }; var ref = function(value) { if (value && value.then) return value; return { then: function(callback) { var result = defer(); nextTick(function() { result.resolve(callback(value)); }); return result.promise; } }; }; /** * @ngdoc * @name ng.$q#reject * @methodOf ng.$q * @description * Creates a promise that is resolved as rejected with the specified `reason`. This api should be * used to forward rejection in a chain of promises. If you are dealing with the last promise in * a promise chain, you don't need to worry about it. * * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via * a promise error callback and you want to forward the error to the promise derived from the * current promise, you have to "rethrow" the error by returning a rejection constructed via * `reject`. * * <pre> * promiseB = promiseA.then(function(result) { * // success: do something and resolve promiseB * // with the old or a new result * return result; * }, function(reason) { * // error: handle the error if possible and * // resolve promiseB with newPromiseOrValue, * // otherwise forward the rejection to promiseB * if (canHandle(reason)) { * // handle the error and recover * return newPromiseOrValue; * } * return $q.reject(reason); * }); * </pre> * * @param {*} reason Constant, message, exception or an object representing the rejection reason. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. */ var reject = function(reason) { return { then: function(callback, errback) { var result = defer(); nextTick(function() { result.resolve((errback || defaultErrback)(reason)); }); return result.promise; } }; }; /** * @ngdoc * @name ng.$q#when * @methodOf ng.$q * @description * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. * This is useful when you are dealing with an object that might or might not be a promise, or if * the promise comes from a source that can't be trusted. * * @param {*} value Value or a promise * @returns {Promise} Returns a promise of the passed value or promise */ var when = function(value, callback, errback) { var result = defer(), done; var wrappedCallback = function(value) { try { return (callback || defaultCallback)(value); } catch (e) { exceptionHandler(e); return reject(e); } }; var wrappedErrback = function(reason) { try { return (errback || defaultErrback)(reason); } catch (e) { exceptionHandler(e); return reject(e); } }; nextTick(function() { ref(value).then(function(value) { if (done) return; done = true; result.resolve(ref(value).then(wrappedCallback, wrappedErrback)); }, function(reason) { if (done) return; done = true; result.resolve(wrappedErrback(reason)); }); }); return result.promise; }; function defaultCallback(value) { return value; } function defaultErrback(reason) { return reject(reason); } /** * @ngdoc * @name ng.$q#all * @methodOf ng.$q * @description * Combines multiple promises into a single promise that is resolved when all of the input * promises are resolved. * * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, * each value corresponding to the promise at the same index/key in the `promises` array/hash. If any of * the promises is resolved with a rejection, this resulting promise will be resolved with the * same rejection. */ function all(promises) { var deferred = defer(), counter = 0, results = isArray(promises) ? [] : {}; forEach(promises, function(promise, key) { counter++; ref(promise).then(function(value) { if (results.hasOwnProperty(key)) return; results[key] = value; if (!(--counter)) deferred.resolve(results); }, function(reason) { if (results.hasOwnProperty(key)) return; deferred.reject(reason); }); }); if (counter === 0) { deferred.resolve(results); } return deferred.promise; } return { defer: defer, reject: reject, when: when, all: all }; } /** * @ngdoc object * @name ng.$routeProvider * @function * * @description * * Used for configuring routes. See {@link ng.$route $route} for an example. */ function $RouteProvider(){ var routes = {}; /** * @ngdoc method * @name ng.$routeProvider#when * @methodOf ng.$routeProvider * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redundant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exactly match the * route definition. * * * `path` can contain named groups starting with a colon (`:name`). All characters up * to the next slash are matched and stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain named groups starting with a star (`*name`). All characters are * eagerly stored in `$routeParams` under the given `name` when the route matches. * * For example, routes like `/color/:color/largecode/*largecode/edit` will match * `/color/brown/largecode/code/with/slashs/edit` and extract: * * * `color: brown` * * `largecode: code/with/slashs`. * * * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly * created scope or the name of a {@link angular.Module#controller registered controller} * if passed as a string. * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be * published to scope under the `controllerAs` name. * - `template` – `{string=|function()=}` – html template as a string or function that returns * an html template as a string which should be used by {@link ng.directive:ngView ngView} or * {@link ng.directive:ngInclude ngInclude} directives. * This property takes precedence over `templateUrl`. * * If `template` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html * template that should be used by {@link ng.directive:ngView ngView}. * * If `templateUrl` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, they will be * resolved and converted to a value before the controller is instantiated and the * `$routeChangeSuccess` event is fired. The map object is: * * - `key` – `{string}`: a name of a dependency to be injected into the controller. * - `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is resolved * before its value is injected into the controller. * * - `redirectTo` – {(string|function())=} – value to update * {@link ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route templateUrl. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search() * changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive * * If the option is set to `true`, then the particular route can be matched without being * case sensitive * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { routes[path] = extend({reloadOnSearch: true, caseInsensitiveMatch: false}, route); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length-1] == '/') ? path.substr(0, path.length-1) : path +'/'; routes[redirectPath] = {redirectTo: path}; } return this; }; /** * @ngdoc method * @name ng.$routeProvider#otherwise * @methodOf ng.$routeProvider * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. * @returns {Object} self */ this.otherwise = function(params) { this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) { /** * @ngdoc object * @name ng.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * The route definition contains: * * - `controller`: The controller constructor as define in route definition. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for * controller instantiation. The `locals` contain * the resolved values of the `resolve` map. Additionally the `locals` also contain: * * - `$scope` - The current route scope. * - `$template` - The current route template HTML. * * @property {Array.<Object>} routes Array of all configured routes. * * @description * Is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * You can define routes through {@link ng.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView} * directive and the {@link ng.$routeParams $routeParams} service. * * @example This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial. Note that this example is using {@link ng.directive:script inlined templates} to get it working on jsfiddle as well. <example module="ngView"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngView', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, resolve: { // I will cause a 1 second delay delay: function($q, $timeout) { var delay = $q.defer(); $timeout(delay.resolve, 1000); return delay.promise; } } }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="scenario.js"> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); sleep(2); // promises are not part of scenario waiting content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ng.$route#$routeChangeStart * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. At this point the route services starts * resolving all of the dependencies needed for the route change to occurs. * Typically this involves fetching the view template as well as any dependencies * defined in `resolve` route property. Once all of the dependencies are resolved * `$routeChangeSuccess` is fired. * * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name ng.$route#$routeChangeSuccess * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted after a route dependencies are resolved. * {@link ng.directive:ngView ngView} listens for the directive * to instantiate the controller and render the view. * * @param {Object} angularEvent Synthetic event object. * @param {Route} current Current route information. * @param {Route|Undefined} previous Previous route information, or undefined if current is first route entered. */ /** * @ngdoc event * @name ng.$route#$routeChangeError * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted if any of the resolve promises are rejected. * * @param {Route} current Current route information. * @param {Route} previous Previous route information. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. */ /** * @ngdoc event * @name ng.$route#$routeUpdate * @eventOf ng.$route * @eventType broadcast on root scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name ng.$route#reload * @methodOf ng.$route * * @description * Causes `$route` service to reload the current route even if * {@link ng.$location $location} hasn't changed. * * As a result of that, {@link ng.directive:ngView ngView} * creates new scope, reinstantiates the controller. */ reload: function() { forceReload = true; $rootScope.$evalAsync(updateRoute); } }; $rootScope.$on('$locationChangeSuccess', updateRoute); return $route; ///////////////////////////////////////////////////// /** * @param on {string} current url * @param when {string} route when template to match the url against * @param whenProperties {Object} properties to define when's matching behavior * @return {?Object} */ function switchRouteMatcher(on, when, whenProperties) { // TODO(i): this code is convoluted and inefficient, we should construct the route matching // regex only once and then reuse it // Escape regexp special characters. when = '^' + when.replace(/[-\/\\^$:*+?.()|[\]{}]/g, "\\$&") + '$'; var regex = '', params = [], dst = {}; var re = /\\([:*])(\w+)/g, paramMatch, lastMatchedIndex = 0; while ((paramMatch = re.exec(when)) !== null) { // Find each :param in `when` and replace it with a capturing group. // Append all other sections of when unchanged. regex += when.slice(lastMatchedIndex, paramMatch.index); switch(paramMatch[1]) { case ':': regex += '([^\\/]*)'; break; case '*': regex += '(.*)'; break; } params.push(paramMatch[2]); lastMatchedIndex = re.lastIndex; } // Append trailing path part. regex += when.substr(lastMatchedIndex); var match = on.match(new RegExp(regex, whenProperties.caseInsensitiveMatch ? 'i' : '')); if (match) { forEach(params, function(name, index) { dst[name] = match[index + 1]; }); } return match ? dst : null; } function updateRoute() { var next = parseRoute(), last = $route.current; if (next && last && next.$$route === last.$$route && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { last.params = next.params; copy(last.params, $routeParams); $rootScope.$broadcast('$routeUpdate', last); } else if (next || last) { forceReload = false; $rootScope.$broadcast('$routeChangeStart', next, last); $route.current = next; if (next) { if (next.redirectTo) { if (isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } } $q.when(next). then(function() { if (next) { var locals = extend({}, next.resolve), template; forEach(locals, function(value, key) { locals[key] = isString(value) ? $injector.get(value) : $injector.invoke(value); }); if (isDefined(template = next.template)) { if (isFunction(template)) { template = template(next.params); } } else if (isDefined(template = next.templateUrl)) { if (isFunction(template)) { template = template(next.params); } if (isDefined(template)) { next.loadedTemplateUrl = template; template = $http.get(template, {cache: $templateCache}). then(function(response) { return response.data; }); } } if (isDefined(template)) { locals['$template'] = template; } return $q.all(locals); } }). // after route change then(function(locals) { if (next == $route.current) { if (next) { next.locals = locals; copy(next.params, $routeParams); } $rootScope.$broadcast('$routeChangeSuccess', next, last); } }, function(error) { if (next == $route.current) { $rootScope.$broadcast('$routeChangeError', next, last, error); } }); } } /** * @returns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; forEach(routes, function(route, path) { if (!match && (params = switchRouteMatcher($location.path(), path, route))) { match = inherit(route, { params: extend({}, $location.search(), params), pathParams: params}); match.$$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parameters */ function interpolate(string, params) { var result = []; forEach((string||'').split(':'), function(segment, i) { if (i == 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } /** * @ngdoc object * @name ng.$routeParams * @requires $route * * @description * Current set of route parameters. The route parameters are a combination of the * {@link ng.$location $location} `search()`, and `path()`. The `path` parameters * are extracted when the {@link ng.$route $route} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ function $RouteParamsProvider() { this.$get = valueFn({}); } /** * DESIGN NOTES * * The design decisions behind the scope are heavily favored for speed and memory consumption. * * The typical use of scope is to watch the expressions, which most of the time return the same * value as last time so we optimize the operation. * * Closures construction is expensive in terms of speed as well as memory: * - No closures, instead use prototypical inheritance for API * - Internal state needs to be stored on scope directly, which means that private state is * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } * - this means that in order to keep the same order of execution as addition we have to add * items to the array at the beginning (shift) instead of at the end (push) * * Child scopes are created and removed often * - Using an array would be slow since inserts in middle are expensive so we use linked list * * There are few watches then a lot of observers. This is why you don't want the observer to be * implemented in the same way as watch. Watch requires return of initialization function which * are expensive to construct. */ /** * @ngdoc object * @name ng.$rootScopeProvider * @description * * Provider for the $rootScope service. */ /** * @ngdoc function * @name ng.$rootScopeProvider#digestTtl * @methodOf ng.$rootScopeProvider * @description * * Sets the number of digest iterations the scope should attempt to execute before giving up and * assuming that the model is unstable. * * The current default is 10 iterations. * * @param {number} limit The number of digest iterations. */ /** * @ngdoc object * @name ng.$rootScope * @description * * Every application has a single root {@link ng.$rootScope.Scope scope}. * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide * event processing life-cycle. See {@link guide/scope developer guide on scopes}. */ function $RootScopeProvider(){ var TTL = 10; this.digestTtl = function(value) { if (arguments.length) { TTL = value; } return TTL; }; this.$get = ['$injector', '$exceptionHandler', '$parse', function( $injector, $exceptionHandler, $parse) { /** * @ngdoc function * @name ng.$rootScope.Scope * * @description * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the * {@link AUTO.$injector $injector}. Child scopes are created using the * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when * compiled HTML template is executed.) * * Here is a simple scope snippet to show how you can interact with the scope. * <pre> * <file src="./test/ng/rootScopeSpec.js" tag="docs1" /> * </pre> * * # Inheritance * A scope can inherit from a parent scope, as in this example: * <pre> var parent = $rootScope; var child = parent.$new(); parent.salutation = "Hello"; child.name = "World"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * </pre> * * * @param {Object.<string, function()>=} providers Map of service factory which need to be provided * for the current scope. Defaults to {@link ng}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. This is handy when unit-testing and having * the need to override a default service. * @returns {Object} Newly created scope. * */ function Scope() { this.$id = nextUid(); this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; this['this'] = this.$root = this; this.$$destroyed = false; this.$$asyncQueue = []; this.$$listeners = {}; this.$$isolateBindings = {}; } /** * @ngdoc property * @name ng.$rootScope.Scope#$id * @propertyOf ng.$rootScope.Scope * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for * debugging. */ Scope.prototype = { /** * @ngdoc function * @name ng.$rootScope.Scope#$new * @methodOf ng.$rootScope.Scope * @function * * @description * Creates a new child {@link ng.$rootScope.Scope scope}. * * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope * hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. * * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for * the scope and its child scopes to be permanently detached from the parent and thus stop * participating in model change detection and listener notification by invoking. * * @param {boolean} isolate if true then the scope does not prototypically inherit from the * parent scope. The scope is isolated, as it can not see parent scope properties. * When creating widgets it is useful for the widget to not accidentally read parent * state. * * @returns {Object} The newly created child scope. * */ $new: function(isolate) { var Child, child; if (isFunction(isolate)) { // TODO: remove at some point throw Error('API-CHANGE: Use $controller to instantiate controllers.'); } if (isolate) { child = new Scope(); child.$root = this.$root; } else { Child = function() {}; // should be anonymous; This is so that when the minifier munges // the name it does not become random set of chars. These will then show up as class // name in the debugger. Child.prototype = this; child = new Child(); child.$id = nextUid(); } child['this'] = child; child.$$listeners = {}; child.$parent = this; child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; child.$$prevSibling = this.$$childTail; if (this.$$childHead) { this.$$childTail.$$nextSibling = child; this.$$childTail = child; } else { this.$$childHead = this.$$childTail = child; } return child; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$watch * @methodOf ng.$rootScope.Scope * @function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and * should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()} * reruns when it detects changes the `watchExpression` can execute multiple times per * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression` are not equal (with the exception of the initial run, * see below). The inequality is determined according to * {@link angular.equals} function. To save the value of the object for later comparison, the * {@link angular.copy} function is used. It also means that watching complex options will * have adverse memory and performance implications. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This * is achieved by rerunning the watchers until no changes are detected. The rerun iteration * limit is 10 to prevent an infinite loop deadlock. * * * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is * detected, be prepared for multiple calls to your listener.) * * After a watcher is registered with the scope, the `listener` fn is called asynchronously * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the * watcher. In rare cases, this is undesirable because the listener is called when the result * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * * * # Example * <pre> // let's assume that scope was dependency injected as the $rootScope var scope = $rootScope; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); * </pre> * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a * call to the `listener`. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {(function()|string)=} listener Callback called whenever the return value of * the `watchExpression` changes. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters. * * @param {boolean=} objectEquality Compare object for equality rather than for reference. * @returns {function()} Returns a deregistration function for this listener. */ $watch: function(watchExp, listener, objectEquality) { var scope = this, get = compileToFn(watchExp, 'watch'), array = scope.$$watchers, watcher = { fn: listener, last: initWatchVal, get: get, exp: watchExp, eq: !!objectEquality }; // in the case user pass string, we need to compile it, do we really need this ? if (!isFunction(listener)) { var listenFn = compileToFn(listener || noop, 'listener'); watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; } if (typeof watchExp == 'string' && get.constant) { var originalFn = watcher.fn; watcher.fn = function(newVal, oldVal, scope) { originalFn.call(this, newVal, oldVal, scope); arrayRemove(array, watcher); }; } if (!array) { array = scope.$$watchers = []; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); return function() { arrayRemove(array, watcher); }; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$watchCollection * @methodOf ng.$rootScope.Scope * @function * * @description * Shallow watches the properties of an object and fires whenever any of the properties change * (for arrays this implies watching the array items, for object maps this implies watching the properties). * If a change is detected the `listener` callback is fired. * * - The `obj` collection is observed via standard $watch operation and is examined on every call to $digest() to * see if any items have been added, removed, or moved. * - The `listener` is called whenever anything within the `obj` has changed. Examples include adding new items * into the object or array, removing and moving items around. * * * # Example * <pre> $scope.names = ['igor', 'matias', 'misko', 'james']; $scope.dataCount = 4; $scope.$watchCollection('names', function(newNames, oldNames) { $scope.dataCount = newNames.length; }); expect($scope.dataCount).toEqual(4); $scope.$digest(); //still at 4 ... no changes expect($scope.dataCount).toEqual(4); $scope.names.pop(); $scope.$digest(); //now there's been a change expect($scope.dataCount).toEqual(3); * </pre> * * * @param {string|Function(scope)} obj Evaluated as {@link guide/expression expression}. The expression value * should evaluate to an object or an array which is observed on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the collection will trigger * a call to the `listener`. * * @param {function(newCollection, oldCollection, scope)} listener a callback function that is fired with both * the `newCollection` and `oldCollection` as parameters. * The `newCollection` object is the newly modified data obtained from the `obj` expression and the * `oldCollection` object is a copy of the former collection data. * The `scope` refers to the current scope. * * @returns {function()} Returns a de-registration function for this listener. When the de-registration function is executed * then the internal watch operation is terminated. */ $watchCollection: function(obj, listener) { var self = this; var oldValue; var newValue; var changeDetected = 0; var objGetter = $parse(obj); var internalArray = []; var internalObject = {}; var oldLength = 0; function $watchCollectionWatch() { newValue = objGetter(self); var newLength, key; if (!isObject(newValue)) { if (oldValue !== newValue) { oldValue = newValue; changeDetected++; } } else if (isArrayLike(newValue)) { if (oldValue !== internalArray) { // we are transitioning from something which was not an array into array. oldValue = internalArray; oldLength = oldValue.length = 0; changeDetected++; } newLength = newValue.length; if (oldLength !== newLength) { // if lengths do not match we need to trigger change notification changeDetected++; oldValue.length = oldLength = newLength; } // copy the items to oldValue and look for changes. for (var i = 0; i < newLength; i++) { if (oldValue[i] !== newValue[i]) { changeDetected++; oldValue[i] = newValue[i]; } } } else { if (oldValue !== internalObject) { // we are transitioning from something which was not an object into object. oldValue = internalObject = {}; oldLength = 0; changeDetected++; } // copy the items to oldValue and look for changes. newLength = 0; for (key in newValue) { if (newValue.hasOwnProperty(key)) { newLength++; if (oldValue.hasOwnProperty(key)) { if (oldValue[key] !== newValue[key]) { changeDetected++; oldValue[key] = newValue[key]; } } else { oldLength++; oldValue[key] = newValue[key]; changeDetected++; } } } if (oldLength > newLength) { // we used to have more keys, need to find them and destroy them. changeDetected++; for(key in oldValue) { if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) { oldLength--; delete oldValue[key]; } } } } return changeDetected; } function $watchCollectionAction() { listener(newValue, oldValue, self); } return this.$watch($watchCollectionWatch, $watchCollectionAction); }, /** * @ngdoc function * @name ng.$rootScope.Scope#$digest * @methodOf ng.$rootScope.Scope * @function * * @description * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children. * Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the * `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are * firing. This means that it is possible to get into an infinite loop. This function will throw * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10. * * Usually you don't call `$digest()` directly in * {@link ng.directive:ngController controllers} or in * {@link ng.$compileProvider#directive directives}. * Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a * {@link ng.$compileProvider#directive directives}) will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()} * with no `listener`. * * You may have a need to call `$digest()` from within unit-tests, to simulate the scope * life-cycle. * * # Example * <pre> var scope = ...; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); * </pre> * */ $digest: function() { var watch, value, last, watchers, asyncQueue = this.$$asyncQueue, length, dirty, ttl = TTL, next, current, target = this, watchLog = [], logIdx, logMsg; beginPhase('$digest'); do { // "while dirty" loop dirty = false; current = target; while(asyncQueue.length) { try { current.$eval(asyncQueue.shift()); } catch (e) { $exceptionHandler(e); } } do { // "traverse the scopes" loop if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; while (length--) { try { watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if ((value = watch.get(current)) !== (last = watch.last) && !(watch.eq ? equals(value, last) : (typeof value == 'number' && typeof last == 'number' && isNaN(value) && isNaN(last)))) { dirty = true; watch.last = watch.eq ? copy(value) : value; watch.fn(value, ((last === initWatchVal) ? value : last), current); if (ttl < 5) { logIdx = 4 - ttl; if (!watchLog[logIdx]) watchLog[logIdx] = []; logMsg = (isFunction(watch.exp)) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp; logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); watchLog[logIdx].push(logMsg); } } } catch (e) { $exceptionHandler(e); } } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); if(dirty && !(ttl--)) { clearPhase(); throw Error(TTL + ' $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: ' + toJson(watchLog)); } } while (dirty || asyncQueue.length); clearPhase(); }, /** * @ngdoc event * @name ng.$rootScope.Scope#$destroy * @eventOf ng.$rootScope.Scope * @eventType broadcast on scope being destroyed * * @description * Broadcasted when a scope and its children are being destroyed. */ /** * @ngdoc function * @name ng.$rootScope.Scope#$destroy * @methodOf ng.$rootScope.Scope * @function * * @description * Removes the current scope (and all of its children) from the parent scope. Removal implies * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer * propagate to the current scope and its children. Removal also implies that the current * scope is eligible for garbage collection. * * The `$destroy()` is usually used by directives such as * {@link ng.directive:ngRepeat ngRepeat} for managing the * unrolling of the loop. * * Just before a scope is destroyed a `$destroy` event is broadcasted on this scope. * Application code can register a `$destroy` event handler that will give it chance to * perform any necessary cleanup. */ $destroy: function() { // we can't destroy the root scope or a scope that has been already destroyed if ($rootScope == this || this.$$destroyed) return; var parent = this.$parent; this.$broadcast('$destroy'); this.$$destroyed = true; if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; // This is bogus code that works around Chrome's GC leak // see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$eval * @methodOf ng.$rootScope.Scope * @function * * @description * Executes the `expression` on the current scope returning the result. Any exceptions in the * expression are propagated (uncaught). This is useful when evaluating Angular expressions. * * # Example * <pre> var scope = ng.$rootScope.Scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); * </pre> * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $eval: function(expr, locals) { return $parse(expr)(this, locals); }, /** * @ngdoc function * @name ng.$rootScope.Scope#$evalAsync * @methodOf ng.$rootScope.Scope * @function * * @description * Executes the expression on the current scope at a later point in time. * * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that: * * - it will execute in the current script execution context (before any DOM rendering). * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * */ $evalAsync: function(expr) { this.$$asyncQueue.push(expr); }, /** * @ngdoc function * @name ng.$rootScope.Scope#$apply * @methodOf ng.$rootScope.Scope * @function * * @description * `$apply()` is used to execute an expression in angular from outside of the angular framework. * (For example from browser DOM events, setTimeout, XHR or third party libraries). * Because we are calling into the angular framework we need to perform proper scope life-cycle * of {@link ng.$exceptionHandler exception handling}, * {@link ng.$rootScope.Scope#$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` * <pre> function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } * </pre> * * * Scope's `$apply()` method transitions through the following stages: * * 1. The {@link guide/expression expression} is executed using the * {@link ng.$rootScope.Scope#$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression * was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $apply: function(expr) { try { beginPhase('$apply'); return this.$eval(expr); } catch (e) { $exceptionHandler(e); } finally { clearPhase(); try { $rootScope.$digest(); } catch (e) { $exceptionHandler(e); throw e; } } }, /** * @ngdoc function * @name ng.$rootScope.Scope#$on * @methodOf ng.$rootScope.Scope * @function * * @description * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of * event life cycle. * * The event listener function format is: `function(event, args...)`. The `event` object * passed into the listener has the following attributes: * * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or `$broadcast`-ed. * - `currentScope` - `{Scope}`: the current scope which is handling the event. * - `name` - `{string}`: Name of the event. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel further event * propagation (available only for events that were `$emit`-ed). * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag to true. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. * * @param {string} name Event name to listen on. * @param {function(event, args...)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. */ $on: function(name, listener) { var namedListeners = this.$$listeners[name]; if (!namedListeners) { this.$$listeners[name] = namedListeners = []; } namedListeners.push(listener); return function() { namedListeners[indexOf(namedListeners, listener)] = null; }; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$emit * @methodOf ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event traverses upwards toward the root scope and calls all registered * listeners along the way. The event will stop propagating if one of the listeners cancels it. * * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $emit: function(name, args) { var empty = [], namedListeners, scope = this, stopPropagation = false, event = { name: name, targetScope: scope, stopPropagation: function() {stopPropagation = true;}, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), i, length; do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; for (i=0, length=namedListeners.length; i<length; i++) { // if listeners were deregistered, defragment the array if (!namedListeners[i]) { namedListeners.splice(i, 1); i--; length--; continue; } try { namedListeners[i].apply(null, listenerArgs); if (stopPropagation) return event; } catch (e) { $exceptionHandler(e); } } //traverse upwards scope = scope.$parent; } while (scope); return event; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$broadcast * @methodOf ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event propagates to all direct and indirect scopes of the current scope and * calls all registered listeners along the way. The event cannot be canceled. * * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to broadcast. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $broadcast: function(name, args) { var target = this, current = target, next = target, event = { name: name, targetScope: target, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), listeners, i, length; //down while you can, then up and next sibling or up and next sibling until back at root do { current = next; event.currentScope = current; listeners = current.$$listeners[name] || []; for (i=0, length = listeners.length; i<length; i++) { // if listeners were deregistered, defragment the array if (!listeners[i]) { listeners.splice(i, 1); i--; length--; continue; } try { listeners[i].apply(null, listenerArgs); } catch(e) { $exceptionHandler(e); } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); return event; } }; var $rootScope = new Scope(); return $rootScope; function beginPhase(phase) { if ($rootScope.$$phase) { throw Error($rootScope.$$phase + ' already in progress'); } $rootScope.$$phase = phase; } function clearPhase() { $rootScope.$$phase = null; } function compileToFn(exp, name) { var fn = $parse(exp); assertArgFn(fn, name); return fn; } /** * function used as an initial value for watchers. * because it's unique we can easily tell it apart from other values */ function initWatchVal() {} }]; } /** * !!! This is an undocumented "private" service !!! * * @name ng.$sniffer * @requires $window * @requires $document * * @property {boolean} history Does the browser support html5 history api ? * @property {boolean} hashchange Does the browser support hashchange event ? * @property {boolean} transitions Does the browser support CSS transition events ? * @property {boolean} animations Does the browser support CSS animation events ? * * @description * This is very simple implementation of testing browser's features. */ function $SnifferProvider() { this.$get = ['$window', '$document', function($window, $document) { var eventSupport = {}, android = int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), document = $document[0] || {}, vendorPrefix, vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/, bodyStyle = document.body && document.body.style, transitions = false, animations = false, match; if (bodyStyle) { for(var prop in bodyStyle) { if(match = vendorRegex.exec(prop)) { vendorPrefix = match[0]; vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); break; } } transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); } return { // Android has history.pushState, but it does not update location correctly // so let's not use the history API at all. // http://code.google.com/p/android/issues/detail?id=17471 // https://github.com/angular/angular.js/issues/904 history: !!($window.history && $window.history.pushState && !(android < 4)), hashchange: 'onhashchange' in $window && // IE8 compatible mode lies (!document.documentMode || document.documentMode > 7), hasEvent: function(event) { // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have // it. In particular the event is not fired when backspace or delete key are pressed or // when cut operation is performed. if (event == 'input' && msie == 9) return false; if (isUndefined(eventSupport[event])) { var divElm = document.createElement('div'); eventSupport[event] = 'on' + event in divElm; } return eventSupport[event]; }, csp: document.securityPolicy ? document.securityPolicy.isActive : false, vendorPrefix: vendorPrefix, transitions : transitions, animations : animations }; }]; } /** * @ngdoc object * @name ng.$window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overridden, removed or mocked for testing. * * All expressions are evaluated with respect to current scope so they don't * suffer from window globality. * * @example <doc:example> <doc:source> <script> function Ctrl($scope, $window) { $scope.$window = $window; $scope.greeting = 'Hello, World!'; } </script> <div ng-controller="Ctrl"> <input type="text" ng-model="greeting" /> <button ng-click="$window.alert(greeting)">ALERT</button> </div> </doc:source> <doc:scenario> it('should display the greeting in the input box', function() { input('greeting').enter('Hello, E2E Tests'); // If we click the button it will block the test runner // element(':button').click(); }); </doc:scenario> </doc:example> */ function $WindowProvider(){ this.$get = valueFn(window); } /** * Parse headers into key value object * * @param {string} headers Raw headers as a string * @returns {Object} Parsed headers as key value object */ function parseHeaders(headers) { var parsed = {}, key, val, i; if (!headers) return parsed; forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); key = lowercase(trim(line.substr(0, i))); val = trim(line.substr(i + 1)); if (key) { if (parsed[key]) { parsed[key] += ', ' + val; } else { parsed[key] = val; } } }); return parsed; } var IS_SAME_DOMAIN_URL_MATCH = /^(([^:]+):)?\/\/(\w+:{0,1}\w*@)?([\w\.-]*)?(:([0-9]+))?(.*)$/; /** * Parse a request and location URL and determine whether this is a same-domain request. * * @param {string} requestUrl The url of the request. * @param {string} locationUrl The current browser location url. * @returns {boolean} Whether the request is for the same domain. */ function isSameDomain(requestUrl, locationUrl) { var match = IS_SAME_DOMAIN_URL_MATCH.exec(requestUrl); // if requestUrl is relative, the regex does not match. if (match == null) return true; var domain1 = { protocol: match[2], host: match[4], port: int(match[6]) || DEFAULT_PORTS[match[2]] || null, // IE8 sets unmatched groups to '' instead of undefined. relativeProtocol: match[2] === undefined || match[2] === '' }; match = SERVER_MATCH.exec(locationUrl); var domain2 = { protocol: match[1], host: match[3], port: int(match[5]) || DEFAULT_PORTS[match[1]] || null }; return (domain1.protocol == domain2.protocol || domain1.relativeProtocol) && domain1.host == domain2.host && (domain1.port == domain2.port || (domain1.relativeProtocol && domain2.port == DEFAULT_PORTS[domain2.protocol])); } /** * Returns a function that provides access to parsed headers. * * Headers are lazy parsed when first requested. * @see parseHeaders * * @param {(string|Object)} headers Headers to provide access to. * @returns {function(string=)} Returns a getter function which if called with: * * - if called with single an argument returns a single header value or null * - if called with no arguments returns an object containing all headers. */ function headersGetter(headers) { var headersObj = isObject(headers) ? headers : undefined; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { return headersObj[lowercase(name)] || null; } return headersObj; }; } /** * Chain all given functions * * This function is used for both request and response transforming * * @param {*} data Data to transform. * @param {function(string=)} headers Http headers getter fn. * @param {(function|Array.<function>)} fns Function or an array of functions. * @returns {*} Transformed data. */ function transformData(data, headers, fns) { if (isFunction(fns)) return fns(data, headers); forEach(fns, function(fn) { data = fn(data, headers); }); return data; } function isSuccess(status) { return 200 <= status && status < 300; } function $HttpProvider() { var JSON_START = /^\s*(\[|\{[^\{])/, JSON_END = /[\}\]]\s*$/, PROTECTION_PREFIX = /^\)\]\}',?\n/, CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'}; var defaults = this.defaults = { // transform incoming response data transformResponse: [function(data) { if (isString(data)) { // strip json vulnerability protection prefix data = data.replace(PROTECTION_PREFIX, ''); if (JSON_START.test(data) && JSON_END.test(data)) data = fromJson(data, true); } return data; }], // transform outgoing request data transformRequest: [function(d) { return isObject(d) && !isFile(d) ? toJson(d) : d; }], // default headers headers: { common: { 'Accept': 'application/json, text/plain, */*' }, post: CONTENT_TYPE_APPLICATION_JSON, put: CONTENT_TYPE_APPLICATION_JSON, patch: CONTENT_TYPE_APPLICATION_JSON }, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN' }; /** * Are order by request. I.E. they are applied in the same order as * array on request, but revers order on response. */ var interceptorFactories = this.interceptors = []; /** * For historical reasons, response interceptors ordered by the order in which * they are applied to response. (This is in revers to interceptorFactories) */ var responseInterceptorFactories = this.responseInterceptors = []; this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { var defaultCache = $cacheFactory('$http'); /** * Interceptors stored in reverse order. Inner interceptors before outer interceptors. * The reversal is needed so that we can build up the interception chain around the * server request. */ var reversedInterceptors = []; forEach(interceptorFactories, function(interceptorFactory) { reversedInterceptors.unshift(isString(interceptorFactory) ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); }); forEach(responseInterceptorFactories, function(interceptorFactory, index) { var responseFn = isString(interceptorFactory) ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory); /** * Response interceptors go before "around" interceptors (no real reason, just * had to pick one.) But they are already revesed, so we can't use unshift, hence * the splice. */ reversedInterceptors.splice(index, 0, { response: function(response) { return responseFn($q.when(response)); }, responseError: function(response) { return responseFn($q.reject(response)); } }); }); /** * @ngdoc function * @name ng.$http * @requires $httpBackend * @requires $browser * @requires $cacheFactory * @requires $rootScope * @requires $q * @requires $injector * * @description * The `$http` service is a core Angular service that facilitates communication with the remote * HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}. * * For unit testing applications that use `$http` service, see * {@link ngMock.$httpBackend $httpBackend mock}. * * For a higher level of abstraction, please check out the {@link ngResource.$resource * $resource} service. * * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage * it is important to familiarize yourself with these APIs and the guarantees they provide. * * * # General usage * The `$http` service is a function which takes a single argument — a configuration object — * that is used to generate an HTTP request and returns a {@link ng.$q promise} * with two $http specific methods: `success` and `error`. * * <pre> * $http({method: 'GET', url: '/someUrl'}). * success(function(data, status, headers, config) { * // this callback will be called asynchronously * // when the response is available * }). * error(function(data, status, headers, config) { * // called asynchronously if an error occurs * // or server returns response with an error status. * }); * </pre> * * Since the returned value of calling the $http function is a `promise`, you can also use * the `then` method to register callbacks, and these callbacks will receive a single argument – * an object representing the response. See the API signature and type info below for more * details. * * A response status code between 200 and 299 is considered a success status and * will result in the success callback being called. Note that if the response is a redirect, * XMLHttpRequest will transparently follow it, meaning that the error callback will not be * called for such responses. * * # Shortcut methods * * Since all invocations of the $http service require passing in an HTTP method and URL, and * POST/PUT requests require request data to be provided as well, shortcut methods * were created: * * <pre> * $http.get('/someUrl').success(successCallback); * $http.post('/someUrl', data).success(successCallback); * </pre> * * Complete list of shortcut methods: * * - {@link ng.$http#get $http.get} * - {@link ng.$http#head $http.head} * - {@link ng.$http#post $http.post} * - {@link ng.$http#put $http.put} * - {@link ng.$http#delete $http.delete} * - {@link ng.$http#jsonp $http.jsonp} * * * # Setting HTTP Headers * * The $http service will automatically add certain HTTP headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, * / *` * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) * - `Content-Type: application/json` * * To add or overwrite these defaults, simply add or remove a property from these configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with the lowercased HTTP method name as the key, e.g. * `$httpProvider.defaults.headers.get['My-Header']='value'`. * * Additionally, the defaults can be set at runtime via the `$http.defaults` object in the same * fashion. * * * # Transforming Requests and Responses * * Both requests and responses can be transformed using transform functions. By default, Angular * applies these transformations: * * Request transformations: * * - If the `data` property of the request configuration object contains an object, serialize it into * JSON format. * * Response transformations: * * - If XSRF prefix is detected, strip it (see Security Considerations section below). * - If JSON response is detected, deserialize it using a JSON parser. * * To globally augment or override the default transforms, modify the `$httpProvider.defaults.transformRequest` and * `$httpProvider.defaults.transformResponse` properties. These properties are by default an * array of transform functions, which allows you to `push` or `unshift` a new transformation function into the * transformation chain. You can also decide to completely override any default transformations by assigning your * transformation functions to these properties directly without the array wrapper. * * Similarly, to locally override the request/response transforms, augment the `transformRequest` and/or * `transformResponse` properties of the configuration object passed into `$http`. * * * # Caching * * To enable caching, set the configuration property `cache` to `true`. When the cache is * enabled, `$http` stores the response from the server in local cache. Next time the * response is served from the cache without sending a request to the server. * * Note that even if the response is served from cache, delivery of the data is asynchronous in * the same way that real requests are. * * If there are multiple GET requests for the same URL that should be cached using the same * cache, but the cache is not populated yet, only one request to the server will be made and * the remaining requests will be fulfilled using the response from the first request. * * A custom default cache built with $cacheFactory can be provided in $http.defaults.cache. * To skip it, set configuration property `cache` to `false`. * * * # Interceptors * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication, or any kind of synchronous or * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be * able to intercept requests before they are handed to the server and * responses before they are handed over to the application code that * initiated these requests. The interceptors leverage the {@link ng.$q * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. * * The interceptors are service factories that are registered with the `$httpProvider` by * adding them to the `$httpProvider.interceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor. * * There are two kinds of interceptors (and two kinds of rejection interceptors): * * * `request`: interceptors get called with http `config` object. The function is free to modify * the `config` or create a new one. The function needs to return the `config` directly or as a * promise. * * `requestError`: interceptor gets called when a previous interceptor threw an error or resolved * with a rejection. * * `response`: interceptors get called with http `response` object. The function is free to modify * the `response` or create a new one. The function needs to return the `response` directly or as a * promise. * * `responseError`: interceptor gets called when a previous interceptor threw an error or resolved * with a rejection. * * * <pre> * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return { * // optional method * 'request': function(config) { * // do something on success * return config || $q.when(config); * }, * * // optional method * 'requestError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * }, * * * * // optional method * 'response': function(response) { * // do something on success * return response || $q.when(response); * }, * * // optional method * 'responseError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * }; * } * }); * * $httpProvider.interceptors.push('myHttpInterceptor'); * * * // register the interceptor via an anonymous factory * $httpProvider.interceptors.push(function($q, dependency1, dependency2) { * return { * 'request': function(config) { * // same as above * }, * 'response': function(response) { * // same as above * } * }); * </pre> * * # Response interceptors (DEPRECATED) * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication or any kind of synchronous or * asynchronous preprocessing of received responses, it is desirable to be able to intercept * responses for http requests before they are handed over to the application code that * initiated these requests. The response interceptors leverage the {@link ng.$q * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. * * The interceptors are service factories that are registered with the $httpProvider by * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor — a function that * takes a {@link ng.$q promise} and returns the original or a new promise. * * <pre> * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return function(promise) { * return promise.then(function(response) { * // do something on success * }, function(response) { * // do something on error * if (canRecover(response)) { * return responseOrNewPromise * } * return $q.reject(response); * }); * } * }); * * $httpProvider.responseInterceptors.push('myHttpInterceptor'); * * * // register the interceptor via an anonymous factory * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) { * return function(promise) { * // same as above * } * }); * </pre> * * * # Security Considerations * * When designing web applications, consider security threats from: * * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON vulnerability} * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} * * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ## JSON Vulnerability Protection * * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON vulnerability} allows third party website to turn your JSON resource URL into * {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * <pre> * ['one','two'] * </pre> * * which is vulnerable to attack, your server can return: * <pre> * )]}', * ['one','two'] * </pre> * * Angular will strip the prefix, before processing the JSON. * * * ## Cross Site Request Forgery (XSRF) Protection * * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which * an unauthorized site can gain your user's private data. Angular provides a mechanism * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only * JavaScript that runs on your domain could read the cookie, your server can be assured that * the XHR came from JavaScript running on your domain. The header will not be set for * cross-domain requests. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure * that only JavaScript running on your domain could have sent the request. The token must be * unique for each user and must be verifiable by the server (to prevent the JavaScript from making * up its own tokens). We recommend that the token is a digest of your site's authentication * cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt} for added security. * * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName * properties of either $httpProvider.defaults, or the per-request config object. * * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. * - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * response body and headers and returns its transformed (typically deserialized) version. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for * caching. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} * that should abort the request when resolved. * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 * requests with credentials} for more information. * - **responseType** - `{string}` - see {@link * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}. * * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the * standard `then` method and two http specific methods: `success` and `error`. The `then` * method takes two arguments a success and an error callback which will be called with a * response object. The `success` and `error` methods take a single argument - a function that * will be called when the request succeeds or fails respectively. The arguments passed into * these functions are destructured representation of the response object passed into the * `then` method. The response object has these properties: * * - **data** – `{string|Object}` – The response body transformed with the transform functions. * - **status** – `{number}` – HTTP status code of the response. * - **headers** – `{function([headerName])}` – Header getter function. * - **config** – `{Object}` – The configuration object that was used to generate the request. * * @property {Array.<Object>} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example <example> <file name="index.html"> <div ng-controller="FetchCtrl"> <select ng-model="method"> <option>GET</option> <option>JSONP</option> </select> <input type="text" ng-model="url" size="80"/> <button ng-click="fetch()">fetch</button><br> <button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button> <pre>http status code: {{status}}</pre> <pre>http response data: {{data}}</pre> </div> </file> <file name="script.js"> function FetchCtrl($scope, $http, $templateCache) { $scope.method = 'GET'; $scope.url = 'http-hello.html'; $scope.fetch = function() { $scope.code = null; $scope.response = null; $http({method: $scope.method, url: $scope.url, cache: $templateCache}). success(function(data, status) { $scope.status = status; $scope.data = data; }). error(function(data, status) { $scope.data = data || "Request failed"; $scope.status = status; }); }; $scope.updateModel = function(method, url) { $scope.method = method; $scope.url = url; }; } </file> <file name="http-hello.html"> Hello, $http! </file> <file name="scenario.js"> it('should make an xhr GET request', function() { element(':button:contains("Sample GET")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toMatch(/Hello, \$http!/); }); it('should make a JSONP request to angularjs.org', function() { element(':button:contains("Sample JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toMatch(/Super Hero!/); }); it('should make JSONP request to invalid URL and invoke the error handler', function() { element(':button:contains("Invalid JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('0'); expect(binding('data')).toBe('Request failed'); }); </file> </example> */ function $http(requestConfig) { var config = { transformRequest: defaults.transformRequest, transformResponse: defaults.transformResponse }; var headers = {}; extend(config, requestConfig); config.headers = headers; config.method = uppercase(config.method); extend(headers, defaults.headers.common, defaults.headers[lowercase(config.method)], requestConfig.headers); var xsrfValue = isSameDomain(config.url, $browser.url()) ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] : undefined; if (xsrfValue) { headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; } var serverRequest = function(config) { var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); // strip content-type if data is undefined if (isUndefined(config.data)) { delete headers['Content-Type']; } if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { config.withCredentials = defaults.withCredentials; } // send request return sendReq(config, reqData, headers).then(transformResponse, transformResponse); }; var chain = [serverRequest, undefined]; var promise = $q.when(config); // apply interceptors forEach(reversedInterceptors, function(interceptor) { if (interceptor.request || interceptor.requestError) { chain.unshift(interceptor.request, interceptor.requestError); } if (interceptor.response || interceptor.responseError) { chain.push(interceptor.response, interceptor.responseError); } }); while(chain.length) { var thenFn = chain.shift(); var rejectFn = chain.shift(); promise = promise.then(thenFn, rejectFn); } promise.success = function(fn) { promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; return promise; function transformResponse(response) { // make a copy since the response must be cacheable var resp = extend({}, response, { data: transformData(response.data, response.headers, config.transformResponse) }); return (isSuccess(response.status)) ? resp : $q.reject(resp); } } $http.pendingRequests = []; /** * @ngdoc method * @name ng.$http#get * @methodOf ng.$http * * @description * Shortcut method to perform `GET` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#delete * @methodOf ng.$http * * @description * Shortcut method to perform `DELETE` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#head * @methodOf ng.$http * * @description * Shortcut method to perform `HEAD` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#jsonp * @methodOf ng.$http * * @description * Shortcut method to perform `JSONP` request. * * @param {string} url Relative or absolute URL specifying the destination of the request. * Should contain `JSON_CALLBACK` string. * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethods('get', 'delete', 'head', 'jsonp'); /** * @ngdoc method * @name ng.$http#post * @methodOf ng.$http * * @description * Shortcut method to perform `POST` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#put * @methodOf ng.$http * * @description * Shortcut method to perform `PUT` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethodsWithData('post', 'put'); /** * @ngdoc property * @name ng.$http#defaults * @propertyOf ng.$http * * @description * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of * default headers, withCredentials as well as request and response transformations. * * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. */ $http.defaults = defaults; return $http; function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { return $http(extend(config || {}, { method: name, url: url })); }; }); } function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { return $http(extend(config || {}, { method: name, url: url, data: data })); }; }); } /** * Makes the request. * * !!! ACCESSES CLOSURE VARS: * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests */ function sendReq(config, reqData, reqHeaders) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, url = buildUrl(config.url, config.params); $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') { cache = isObject(config.cache) ? config.cache : isObject(defaults.cache) ? defaults.cache : defaultCache; } if (cache) { cachedResp = cache.get(url); if (cachedResp) { if (cachedResp.then) { // cached request has already been sent, but there is no response yet cachedResp.then(removePendingReq, removePendingReq); return cachedResp; } else { // serving from cache if (isArray(cachedResp)) { resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2])); } else { resolvePromise(cachedResp, 200, {}); } } } else { // put the promise for the non-transformed response into cache as a placeholder cache.put(url, promise); } } // if we won't have the response in cache, send the request to the backend if (!cachedResp) { $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, config.withCredentials, config.responseType); } return promise; /** * Callback registered to $httpBackend(): * - caches the response if desired * - resolves the raw $http promise * - calls $apply */ function done(status, response, headersString) { if (cache) { if (isSuccess(status)) { cache.put(url, [status, response, parseHeaders(headersString)]); } else { // remove promise from the cache cache.remove(url); } } resolvePromise(response, status, headersString); if (!$rootScope.$$phase) $rootScope.$apply(); } /** * Resolves the raw $http promise. */ function resolvePromise(response, status, headers) { // normalize internal statuses to 0 status = Math.max(status, 0); (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config }); } function removePendingReq() { var idx = indexOf($http.pendingRequests, config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } function buildUrl(url, params) { if (!params) return url; var parts = []; forEachSorted(params, function(value, key) { if (value == null || value == undefined) return; if (!isArray(value)) value = [value]; forEach(value, function(v) { if (isObject(v)) { v = toJson(v); } parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(v)); }); }); return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); } }]; } var XHR = window.XMLHttpRequest || function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} throw new Error("This browser does not support XMLHttpRequest."); }; /** * @ngdoc object * @name ng.$httpBackend * @requires $browser * @requires $window * @requires $document * * @description * HTTP backend used by the {@link ng.$http service} that delegates to * XMLHttpRequest object or JSONP and deals with browser incompatibilities. * * You should never need to use this service directly, instead use the higher-level abstractions: * {@link ng.$http $http} or {@link ngResource.$resource $resource}. * * During testing this implementation is swapped with {@link ngMock.$httpBackend mock * $httpBackend} which can be trained with responses. */ function $HttpBackendProvider() { this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks, $document[0], $window.location.protocol.replace(':', '')); }]; } function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) { // TODO(vojta): fix the signature return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { var status; $browser.$$incOutstandingRequestCount(); url = url || $browser.url(); if (lowercase(method) == 'jsonp') { var callbackId = '_' + (callbacks.counter++).toString(36); callbacks[callbackId] = function(data) { callbacks[callbackId].data = data; }; var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), function() { if (callbacks[callbackId].data) { completeRequest(callback, 200, callbacks[callbackId].data); } else { completeRequest(callback, status || -2); } delete callbacks[callbackId]; }); } else { var xhr = new XHR(); xhr.open(method, url, true); forEach(headers, function(value, key) { if (value) xhr.setRequestHeader(key, value); }); // In IE6 and 7, this might be called synchronously when xhr.send below is called and the // response is in the cache. the promise api will ensure that to the app code the api is // always async xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var responseHeaders = xhr.getAllResponseHeaders(); // TODO(vojta): remove once Firefox 21 gets released. // begin: workaround to overcome Firefox CORS http response headers bug // https://bugzilla.mozilla.org/show_bug.cgi?id=608735 // Firefox already patched in nightly. Should land in Firefox 21. // CORS "simple response headers" http://www.w3.org/TR/cors/ var value, simpleHeaders = ["Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma"]; if (!responseHeaders) { responseHeaders = ""; forEach(simpleHeaders, function (header) { var value = xhr.getResponseHeader(header); if (value) { responseHeaders += header + ": " + value + "\n"; } }); } // end of the workaround. // responseText is the old-school way of retrieving response (supported by IE8 & 9) // response and responseType properties were introduced in XHR Level2 spec (supported by IE10) completeRequest(callback, status || xhr.status, (xhr.responseType ? xhr.response : xhr.responseText), responseHeaders); } }; if (withCredentials) { xhr.withCredentials = true; } if (responseType) { xhr.responseType = responseType; } xhr.send(post || ''); } if (timeout > 0) { var timeoutId = $browserDefer(timeoutRequest, timeout); } else if (timeout && timeout.then) { timeout.then(timeoutRequest); } function timeoutRequest() { status = -1; jsonpDone && jsonpDone(); xhr && xhr.abort(); } function completeRequest(callback, status, response, headersString) { // URL_MATCH is defined in src/service/location.js var protocol = (url.match(SERVER_MATCH) || ['', locationProtocol])[1]; // cancel timeout and subsequent timeout promise resolution timeoutId && $browserDefer.cancel(timeoutId); jsonpDone = xhr = null; // fix status code for file protocol (it's always 0) status = (protocol == 'file') ? (response ? 200 : 404) : status; // normalize IE bug (http://bugs.jquery.com/ticket/1450) status = status == 1223 ? 204 : status; callback(status, response, headersString); $browser.$$completeOutstandingRequest(noop); } }; function jsonpReq(url, done) { // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document var script = rawDocument.createElement('script'), doneWrapper = function() { rawDocument.body.removeChild(script); if (done) done(); }; script.type = 'text/javascript'; script.src = url; if (msie) { script.onreadystatechange = function() { if (/loaded|complete/.test(script.readyState)) doneWrapper(); }; } else { script.onload = script.onerror = doneWrapper; } rawDocument.body.appendChild(script); return doneWrapper; } } /** * @ngdoc object * @name ng.$locale * * @description * $locale service provides localization rules for various Angular components. As of right now the * only public api is: * * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) */ function $LocaleProvider(){ this.$get = function() { return { id: 'en-us', NUMBER_FORMATS: { DECIMAL_SEP: '.', GROUP_SEP: ',', PATTERNS: [ { // Decimal Pattern minInt: 1, minFrac: 0, maxFrac: 3, posPre: '', posSuf: '', negPre: '-', negSuf: '', gSize: 3, lgSize: 3 },{ //Currency Pattern minInt: 1, minFrac: 2, maxFrac: 2, posPre: '\u00A4', posSuf: '', negPre: '(\u00A4', negSuf: ')', gSize: 3, lgSize: 3 } ], CURRENCY_SYM: '$' }, DATETIME_FORMATS: { MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' .split(','), SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), AMPMS: ['AM','PM'], medium: 'MMM d, y h:mm:ss a', short: 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }, pluralCat: function(num) { if (num === 1) { return 'one'; } return 'other'; } }; }; } function $TimeoutProvider() { this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler', function($rootScope, $browser, $q, $exceptionHandler) { var deferreds = {}; /** * @ngdoc function * @name ng.$timeout * @requires $browser * * @description * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch * block and delegates any exceptions to * {@link ng.$exceptionHandler $exceptionHandler} service. * * The return value of registering a timeout function is a promise, which will be resolved when * the timeout is reached and the timeout function is executed. * * To cancel a timeout request, call `$timeout.cancel(promise)`. * * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to * synchronously flush the queue of deferred functions. * * @param {function()} fn A function, whose execution should be delayed. * @param {number=} [delay=0] Delay in milliseconds. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this * promise will be resolved with is the return value of the `fn` function. */ function timeout(fn, delay, invokeApply) { var deferred = $q.defer(), promise = deferred.promise, skipApply = (isDefined(invokeApply) && !invokeApply), timeoutId, cleanup; timeoutId = $browser.defer(function() { try { deferred.resolve(fn()); } catch(e) { deferred.reject(e); $exceptionHandler(e); } if (!skipApply) $rootScope.$apply(); }, delay); cleanup = function() { delete deferreds[promise.$$timeoutId]; }; promise.$$timeoutId = timeoutId; deferreds[timeoutId] = deferred; promise.then(cleanup, cleanup); return promise; } /** * @ngdoc function * @name ng.$timeout#cancel * @methodOf ng.$timeout * * @description * Cancels a task associated with the `promise`. As a result of this, the promise will be * resolved with a rejection. * * @param {Promise=} promise Promise returned by the `$timeout` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully * canceled. */ timeout.cancel = function(promise) { if (promise && promise.$$timeoutId in deferreds) { deferreds[promise.$$timeoutId].reject('canceled'); return $browser.defer.cancel(promise.$$timeoutId); } return false; }; return timeout; }]; } /** * @ngdoc object * @name ng.$filterProvider * @description * * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To * achieve this a filter definition consists of a factory function which is annotated with dependencies and is * responsible for creating a filter function. * * <pre> * // Filter registration * function MyModule($provide, $filterProvider) { * // create a service to demonstrate injection (not always needed) * $provide.value('greet', function(name){ * return 'Hello ' + name + '!'; * }); * * // register a filter factory which uses the * // greet service to demonstrate DI. * $filterProvider.register('greet', function(greet){ * // return the filter function which uses the greet service * // to generate salutation * return function(text) { * // filters need to be forgiving so check input validity * return text && greet(text) || text; * }; * }); * } * </pre> * * The filter function is registered with the `$injector` under the filter name suffixe with `Filter`. * <pre> * it('should be the same instance', inject( * function($filterProvider) { * $filterProvider.register('reverse', function(){ * return ...; * }); * }, * function($filter, reverseFilter) { * expect($filter('reverse')).toBe(reverseFilter); * }); * </pre> * * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer * Guide. */ /** * @ngdoc method * @name ng.$filterProvider#register * @methodOf ng.$filterProvider * @description * Register filter factory function. * * @param {String} name Name of the filter. * @param {function} fn The filter factory function which is injectable. */ /** * @ngdoc function * @name ng.$filter * @function * @description * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression [| filter_name[:parameter_value] ... ] }} * * @param {String} name Name of the filter function to retrieve * @return {Function} the filter function */ $FilterProvider.$inject = ['$provide']; function $FilterProvider($provide) { var suffix = 'Filter'; function register(name, factory) { return $provide.factory(name + suffix, factory); } this.register = register; this.$get = ['$injector', function($injector) { return function(name) { return $injector.get(name + suffix); } }]; //////////////////////////////////////// register('currency', currencyFilter); register('date', dateFilter); register('filter', filterFilter); register('json', jsonFilter); register('limitTo', limitToFilter); register('lowercase', lowercaseFilter); register('number', numberFilter); register('orderBy', orderByFilter); register('uppercase', uppercaseFilter); } /** * @ngdoc filter * @name ng.filter:filter * @function * * @description * Selects a subset of items from `array` and returns it as a new array. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: Predicate that results in a substring match using the value of `expression` * string. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * * - `function`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * * @param {function(expected, actual)|true|undefined} comparator Comparator which is used in * determining if the expected value (from the filter expression) and actual value (from * the object in the array) should be considered a match. * * Can be one of: * * - `function(expected, actual)`: * The function will be given the object value and the predicate value to compare and * should return true if the item should be included in filtered result. * * - `true`: A shorthand for `function(expected, actual) { return angular.equals(expected, actual)}`. * this is essentially strict comparison of expected and actual. * * - `false|undefined`: A short hand for a function which will look for a substring match in case * insensitive way. * * @example <doc:example> <doc:source> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}, {name:'Juliette', phone:'555-5678'}]"></div> Search: <input ng-model="searchText"> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th></tr> <tr ng-repeat="friend in friends | filter:searchText"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> </tr> </table> <hr> Any: <input ng-model="search.$"> <br> Name only <input ng-model="search.name"><br> Phone only <input ng-model="search.phone"><br> Equality <input type="checkbox" ng-model="strict"><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th></tr> <tr ng-repeat="friend in friends | filter:search:strict"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> </tr> </table> </doc:source> <doc:scenario> it('should search across all fields when filtering with a string', function() { input('searchText').enter('m'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Adam']); input('searchText').enter('76'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['John', 'Julie']); }); it('should search in specific fields when filtering with a predicate object', function() { input('search.$').enter('i'); expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Julie', 'Juliette']); }); it('should use a equal comparison when comparator is true', function() { input('search.name').enter('Julie'); input('strict').check(); expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). toEqual(['Julie']); }); </doc:scenario> </doc:example> */ function filterFilter() { return function(array, expression, comperator) { if (!isArray(array)) return array; var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; switch(typeof comperator) { case "function": break; case "boolean": if(comperator == true) { comperator = function(obj, text) { return angular.equals(obj, text); } break; } default: comperator = function(obj, text) { text = (''+text).toLowerCase(); return (''+obj).toLowerCase().indexOf(text) > -1 }; } var search = function(obj, text){ if (typeof text == 'string' && text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return comperator(obj, text); case "object": switch (typeof text) { case "object": return comperator(obj, text); break; default: for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } break; } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function() { if (!expression[key]) return; var path = key predicates.push(function(value) { return search(value, expression[path]); }); })(); } else { (function() { if (!expression[key]) return; var path = key; predicates.push(function(value) { return search(getter(value,path), expression[path]); }); })(); } } break; case 'function': predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; } } /** * @ngdoc filter * @name ng.filter:currency * @function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default * symbol for current locale is used. * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. * @returns {string} Formatted number. * * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.amount = 1234.56; } </script> <div ng-controller="Ctrl"> <input type="number" ng-model="amount"> <br> default currency symbol ($): {{amount | currency}}<br> custom currency identifier (USD$): {{amount | currency:"USD$"}} </div> </doc:source> <doc:scenario> it('should init with 1234.56', function() { expect(binding('amount | currency')).toBe('$1,234.56'); expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); }); it('should update', function() { input('amount').enter('-1234'); expect(binding('amount | currency')).toBe('($1,234.00)'); expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)'); }); </doc:scenario> </doc:example> */ currencyFilter.$inject = ['$locale']; function currencyFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(amount, currencySymbol){ if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). replace(/\u00A4/g, currencySymbol); }; } /** * @ngdoc filter * @name ng.filter:number * @function * * @description * Formats a number as text. * * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.val = 1234.56789; } </script> <div ng-controller="Ctrl"> Enter number: <input ng-model='val'><br> Default formatting: {{val | number}}<br> No fractions: {{val | number:0}}<br> Negative number: {{-val | number:4}} </div> </doc:source> <doc:scenario> it('should format numbers', function() { expect(binding('val | number')).toBe('1,234.568'); expect(binding('val | number:0')).toBe('1,235'); expect(binding('-val | number:4')).toBe('-1,234.5679'); }); it('should update', function() { input('val').enter('3374.333'); expect(binding('val | number')).toBe('3,374.333'); expect(binding('val | number:0')).toBe('3,374'); expect(binding('-val | number:4')).toBe('-3,374.3330'); }); </doc:scenario> </doc:example> */ numberFilter.$inject = ['$locale']; function numberFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(number, fractionSize) { return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize); }; } var DECIMAL_SEP = '.'; function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { if (isNaN(number) || !isFinite(number)) return ''; var isNegative = number < 0; number = Math.abs(number); var numStr = number + '', formatedText = '', parts = []; var hasExponent = false; if (numStr.indexOf('e') !== -1) { var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); if (match && match[2] == '-' && match[3] > fractionSize + 1) { numStr = '0'; } else { formatedText = numStr; hasExponent = true; } } if (!hasExponent) { var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; // determine fractionSize if it is not specified if (isUndefined(fractionSize)) { fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); } var pow = Math.pow(10, fractionSize); number = Math.round(number * pow) / pow; var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; var pos = 0, lgroup = pattern.lgSize, group = pattern.gSize; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; for (var i = 0; i < pos; i++) { if ((pos - i)%group === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } } for (i = pos; i < whole.length; i++) { if ((whole.length - i)%lgroup === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } // format fraction part. while(fraction.length < fractionSize) { fraction += '0'; } if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); } parts.push(isNegative ? pattern.negPre : pattern.posPre); parts.push(formatedText); parts.push(isNegative ? pattern.negSuf : pattern.posSuf); return parts.join(''); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { offset = offset || 0; return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date, formats) { var value = date['get' + name](); var get = uppercase(shortForm ? ('SHORT' + name) : name); return formats[get][value]; }; } function timeZoneGetter(date) { var zone = -1 * date.getTimezoneOffset(); var paddedZone = (zone >= 0) ? "+" : ""; paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + padNumber(Math.abs(zone % 60), 2); return paddedZone; } function ampmGetter(date, formats) { return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), // while ISO 8601 requires fractions to be prefixed with `.` or `,` // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions sss: dateGetter('Milliseconds', 3), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, Z: timeZoneGetter }; var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, NUMBER_STRING = /^\d+$/; /** * @ngdoc filter * @name ng.filter:date * @function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) * * `'MMMM'`: Month in year (January-December) * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01-12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) * * `format` string can also be one of the following predefined * {@link guide/i18n localizable formats}: * * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale * (e.g. Sep 3, 2010 12:05:08 pm) * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) * * `format` string can contain literal values. These need to be quoted with single quotes (e.g. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence * (e.g. `"h o''clock"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is * specified in the string input, the time is considered to be in the local timezone. * @param {string=} format Formatting rules (see Description). If not specified, * `mediumDate` is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <doc:example> <doc:source> <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>: {{1288323623006 | date:'medium'}}<br> <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br> <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br> </doc:source> <doc:scenario> it('should format date', function() { expect(binding("1288323623006 | date:'medium'")). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/); expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); }); </doc:scenario> </doc:example> */ dateFilter.$inject = ['$locale']; function dateFilter($locale) { var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; // 1 2 3 4 5 6 7 8 9 10 11 function jsonStringToDate(string) { var match; if (match = string.match(R_ISO8601_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0, dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, timeSetter = match[8] ? date.setUTCHours : date.setHours; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); var h = int(match[4]||0) - tzHour; var m = int(match[5]||0) - tzMin var s = int(match[6]||0); var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000); timeSetter.call(date, h, m, s, ms); return date; } return string; } return function(date, format) { var text = '', parts = [], fn, match; format = format || 'mediumDate'; format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { if (NUMBER_STRING.test(date)) { date = int(date); } else { date = jsonStringToDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } while(format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } forEach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date, $locale.DATETIME_FORMATS) : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); return text; }; } /** * @ngdoc filter * @name ng.filter:json * @function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * * @example: <doc:example> <doc:source> <pre>{{ {'name':'value'} | json }}</pre> </doc:source> <doc:scenario> it('should jsonify filtered objects', function() { expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/); }); </doc:scenario> </doc:example> * */ function jsonFilter() { return function(object) { return toJson(object, true); }; } /** * @ngdoc filter * @name ng.filter:lowercase * @function * @description * Converts string to lowercase. * @see angular.lowercase */ var lowercaseFilter = valueFn(lowercase); /** * @ngdoc filter * @name ng.filter:uppercase * @function * @description * Converts string to uppercase. * @see angular.uppercase */ var uppercaseFilter = valueFn(uppercase); /** * @ngdoc function * @name ng.filter:limitTo * @function * * @description * Creates a new array or string containing only a specified number of elements. The elements * are taken from either the beginning or the end of the source array or string, as specified by * the value and sign (positive or negative) of `limit`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {Array|string} input Source array or string to be limited. * @param {string|number} limit The length of the returned array or string. If the `limit` number * is positive, `limit` number of items from the beginning of the source array/string are copied. * If the number is negative, `limit` number of items from the end of the source array/string * are copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array * had less than `limit` elements. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.numbers = [1,2,3,4,5,6,7,8,9]; $scope.letters = "abcdefghi"; $scope.numLimit = 3; $scope.letterLimit = 3; } </script> <div ng-controller="Ctrl"> Limit {{numbers}} to: <input type="integer" ng-model="numLimit"> <p>Output numbers: {{ numbers | limitTo:numLimit }}</p> Limit {{letters}} to: <input type="integer" ng-model="letterLimit"> <p>Output letters: {{ letters | limitTo:letterLimit }}</p> </div> </doc:source> <doc:scenario> it('should limit the number array to first three items', function() { expect(element('.doc-example-live input[ng-model=numLimit]').val()).toBe('3'); expect(element('.doc-example-live input[ng-model=letterLimit]').val()).toBe('3'); expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3]'); expect(binding('letters | limitTo:letterLimit')).toEqual('abc'); }); it('should update the output when -3 is entered', function() { input('numLimit').enter(-3); input('letterLimit').enter(-3); expect(binding('numbers | limitTo:numLimit')).toEqual('[7,8,9]'); expect(binding('letters | limitTo:letterLimit')).toEqual('ghi'); }); it('should not exceed the maximum size of input array', function() { input('numLimit').enter(100); input('letterLimit').enter(100); expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3,4,5,6,7,8,9]'); expect(binding('letters | limitTo:letterLimit')).toEqual('abcdefghi'); }); </doc:scenario> </doc:example> */ function limitToFilter(){ return function(input, limit) { if (!isArray(input) && !isString(input)) return input; limit = int(limit); if (isString(input)) { //NaN check on limit if (limit) { return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); } else { return ""; } } var out = [], i, n; // if abs(limit) exceeds maximum length, trim it if (limit > input.length) limit = input.length; else if (limit < -input.length) limit = -input.length; if (limit > 0) { i = 0; n = limit; } else { i = input.length + limit; n = input.length; } for (; i<n; i++) { out.push(input[i]); } return out; } } /** * @ngdoc function * @name ng.filter:orderBy * @function * * @description * Orders a specified `array` by the `expression` predicate. * * Note: this function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: Getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name' * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control * ascending or descending sort order (for example, +name or -name). * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * * @param {boolean=} reverse Reverse the order the array. * @returns {Array} Sorted copy of the source array. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}] $scope.predicate = '-age'; } </script> <div ng-controller="Ctrl"> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng-click="predicate=''">unsorted</a> ] <table class="friend"> <tr> <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a> (<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th> <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th> </tr> <tr ng-repeat="friend in friends | orderBy:predicate:reverse"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> </tr> </table> </div> </doc:source> <doc:scenario> it('should be reverse ordered by aged', function() { expect(binding('predicate')).toBe('-age'); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '29', '21', '19', '10']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); }); it('should reorder the table when user selects different predicate', function() { element('.doc-example-live a:contains("Name")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '10', '29', '19', '21']); element('.doc-example-live a:contains("Phone")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.phone')). toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); }); </doc:scenario> </doc:example> */ orderByFilter.$inject = ['$parse']; function orderByFilter($parse){ return function(array, sortPredicate, reverseOrder) { if (!isArray(array)) return array; if (!sortPredicate) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; sortPredicate = map(sortPredicate, function(predicate){ var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } get = $parse(predicate); } return reverseComparator(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2){ for ( var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } } } function ngDirective(directive) { if (isFunction(directive)) { directive = { link: directive } } directive.restrict = directive.restrict || 'AC'; return valueFn(directive); } /** * @ngdoc directive * @name ng.directive:a * @restrict E * * @description * Modifies the default behavior of html A tag, so that the default action is prevented when href * attribute is empty. * * The reasoning for this change is to allow easy creation of action links with `ngClick` directive * without changing the location or causing page reloads, e.g.: * `<a href="" ng-click="model.$save()">Save</a>` */ var htmlAnchorDirective = valueFn({ restrict: 'E', compile: function(element, attr) { if (msie <= 8) { // turn <a href ng-click="..">link</a> into a stylable link in IE // but only if it doesn't have name attribute, in which case it's an anchor if (!attr.href && !attr.name) { attr.$set('href', ''); } // add a comment node to anchors to workaround IE bug that causes element content to be reset // to new attribute content if attribute is updated with value containing @ and element also // contains value with @ // see issue #1949 element.append(document.createComment('IE fix')); } return function(scope, element) { element.bind('click', function(event){ // if we have no href url, then don't navigate anywhere. if (!element.attr('href')) { event.preventDefault(); } }); } } }); /** * @ngdoc directive * @name ng.directive:ngHref * @restrict A * * @description * Using Angular markup like {{hash}} in an href attribute makes * the page open to a wrong URL, if the user clicks that link before * angular has a chance to replace the {{hash}} with actual URL, the * link will be broken and will most likely return a 404 error. * The `ngHref` directive solves this problem. * * The buggy way to write it: * <pre> * <a href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element A * @param {template} ngHref any string which can contain `{{}}` markup. * * @example * This example uses `link` variable inside `href` attribute: <doc:example> <doc:source> <input ng-model="value" /><br /> <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng-href="{{value}}">link</a> (link, change location) </doc:source> <doc:scenario> it('should execute ng-click but not reload when href without value', function() { element('#link-1').click(); expect(input('value').val()).toEqual('1'); expect(element('#link-1').attr('href')).toBe(""); }); it('should execute ng-click but not reload when href empty string', function() { element('#link-2').click(); expect(input('value').val()).toEqual('2'); expect(element('#link-2').attr('href')).toBe(""); }); it('should execute ng-click and change url when ng-href specified', function() { expect(element('#link-3').attr('href')).toBe("/123"); element('#link-3').click(); expect(browser().window().path()).toEqual('/123'); }); it('should execute ng-click but not reload when href empty string and name specified', function() { element('#link-4').click(); expect(input('value').val()).toEqual('4'); expect(element('#link-4').attr('href')).toBe(''); }); it('should execute ng-click but not reload when no href but name specified', function() { element('#link-5').click(); expect(input('value').val()).toEqual('5'); expect(element('#link-5').attr('href')).toBe(undefined); }); it('should only change url when only ng-href', function() { input('value').enter('6'); expect(element('#link-6').attr('href')).toBe('6'); element('#link-6').click(); expect(browser().location().url()).toEqual('/6'); }); </doc:scenario> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngSrc * @restrict A * * @description * Using Angular markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrc` directive solves this problem. * * The buggy way to write it: * <pre> * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element IMG * @param {template} ngSrc any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name ng.directive:ngSrcset * @restrict A * * @description * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrcset` directive solves this problem. * * The buggy way to write it: * <pre> * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/> * </pre> * * The correct way to write it: * <pre> * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/> * </pre> * * @element IMG * @param {template} ngSrcset any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name ng.directive:ngDisabled * @restrict A * * @description * * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: * <pre> * <div ng-init="scope = { isDisabled: false }"> * <button disabled="{{scope.isDisabled}}">Disabled</button> * </div> * </pre> * * The HTML specs do not require browsers to preserve the special attributes such as disabled. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngDisabled` directive. * * @example <doc:example> <doc:source> Click me to toggle: <input type="checkbox" ng-model="checked"><br/> <button ng-model="button" ng-disabled="checked">Button</button> </doc:source> <doc:scenario> it('should toggle button', function() { expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngDisabled Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngChecked * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as checked. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngChecked` directive. * @example <doc:example> <doc:source> Check me to check both: <input type="checkbox" ng-model="master"><br/> <input id="checkSlave" type="checkbox" ng-checked="master"> </doc:source> <doc:scenario> it('should check both checkBoxes', function() { expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy(); input('master').check(); expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngChecked Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngMultiple * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as multiple. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngMultiple` directive. * * @example <doc:example> <doc:source> Check me check multiple: <input type="checkbox" ng-model="checked"><br/> <select id="select" ng-multiple="checked"> <option>Misko</option> <option>Igor</option> <option>Vojta</option> <option>Di</option> </select> </doc:source> <doc:scenario> it('should toggle multiple', function() { expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element SELECT * @param {expression} ngMultiple Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngReadonly * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as readonly. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngReadonly` directive. * @example <doc:example> <doc:source> Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/> <input type="text" ng-readonly="checked" value="I'm Angular"/> </doc:source> <doc:scenario> it('should toggle readonly attr', function() { expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {string} expression Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngSelected * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as selected. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduced the `ngSelected` directive. * @example <doc:example> <doc:source> Check me to select: <input type="checkbox" ng-model="selected"><br/> <select> <option>Hello!</option> <option id="greet" ng-selected="selected">Greetings!</option> </select> </doc:source> <doc:scenario> it('should select Greetings!', function() { expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy(); input('selected').check(); expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element OPTION * @param {string} expression Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngOpen * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as open. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngOpen` directive. * * @example <doc:example> <doc:source> Check me check multiple: <input type="checkbox" ng-model="open"><br/> <details id="details" ng-open="open"> <summary>Show/Hide me</summary> </details> </doc:source> <doc:scenario> it('should toggle open', function() { expect(element('#details').prop('open')).toBeFalsy(); input('open').check(); expect(element('#details').prop('open')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element DETAILS * @param {string} expression Angular expression that will be evaluated. */ var ngAttributeAliasDirectives = {}; // boolean attrs are evaluated forEach(BOOLEAN_ATTR, function(propName, attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 100, compile: function() { return function(scope, element, attr) { scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { attr.$set(attrName, !!value); }); }; } }; }; }); // ng-src, ng-srcset, ng-href are interpolated forEach(['src', 'srcset', 'href'], function(attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 99, // it needs to run after the attributes are interpolated link: function(scope, element, attr) { attr.$observe(normalized, function(value) { if (!value) return; attr.$set(attrName, value); // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need // to set the property as well to achieve the desired effect. // we use attr[attrName] value since $set can sanitize the url. if (msie) element.prop(attrName, attr[attrName]); }); } }; }; }); var nullFormCtrl = { $addControl: noop, $removeControl: noop, $setValidity: noop, $setDirty: noop, $setPristine: noop }; /** * @ngdoc object * @name ng.directive:form.FormController * * @property {boolean} $pristine True if user has not interacted with the form yet. * @property {boolean} $dirty True if user has already interacted with the form. * @property {boolean} $valid True if all of the containing forms and controls are valid. * @property {boolean} $invalid True if at least one containing control or form is invalid. * * @property {Object} $error Is an object hash, containing references to all invalid controls or * forms, where: * * - keys are validation tokens (error names) — such as `required`, `url` or `email`), * - values are arrays of controls or forms that are invalid with given error. * * @description * `FormController` keeps track of all its controls and nested forms as well as state of them, * such as being valid/invalid or dirty/pristine. * * Each {@link ng.directive:form form} directive creates an instance * of `FormController`. * */ //asks for $scope to fool the BC controller module FormController.$inject = ['$element', '$attrs', '$scope']; function FormController(element, attrs) { var form = this, parentForm = element.parent().controller('form') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid errors = form.$error = {}, controls = []; // init state form.$name = attrs.name; form.$dirty = false; form.$pristine = true; form.$valid = true; form.$invalid = false; parentForm.$addControl(form); // Setup initial state of the control element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } form.$addControl = function(control) { controls.push(control); if (control.$name && !form.hasOwnProperty(control.$name)) { form[control.$name] = control; } }; form.$removeControl = function(control) { if (control.$name && form[control.$name] === control) { delete form[control.$name]; } forEach(errors, function(queue, validationToken) { form.$setValidity(validationToken, true, control); }); arrayRemove(controls, control); }; form.$setValidity = function(validationToken, isValid, control) { var queue = errors[validationToken]; if (isValid) { if (queue) { arrayRemove(queue, control); if (!queue.length) { invalidCount--; if (!invalidCount) { toggleValidCss(isValid); form.$valid = true; form.$invalid = false; } errors[validationToken] = false; toggleValidCss(true, validationToken); parentForm.$setValidity(validationToken, true, form); } } } else { if (!invalidCount) { toggleValidCss(isValid); } if (queue) { if (includes(queue, control)) return; } else { errors[validationToken] = queue = []; invalidCount++; toggleValidCss(false, validationToken); parentForm.$setValidity(validationToken, false, form); } queue.push(control); form.$valid = false; form.$invalid = true; } }; form.$setDirty = function() { element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); form.$dirty = true; form.$pristine = false; parentForm.$setDirty(); }; /** * @ngdoc function * @name ng.directive:form.FormController#$setPristine * @methodOf ng.directive:form.FormController * * @description * Sets the form to its pristine state. * * This method can be called to remove the 'ng-dirty' class and set the form to its pristine * state (ng-pristine class). This method will also propagate to all the controls contained * in this form. * * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after * saving or resetting it. */ form.$setPristine = function () { element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); form.$dirty = false; form.$pristine = true; forEach(controls, function(control) { control.$setPristine(); }); }; } /** * @ngdoc directive * @name ng.directive:ngForm * @restrict EAC * * @description * Nestable alias of {@link ng.directive:form `form`} directive. HTML * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a * sub-group of controls needs to be determined. * * @param {string=} name|ngForm Name of the form. If specified, the form controller will be published into * related scope, under this name. * */ /** * @ngdoc directive * @name ng.directive:form * @restrict E * * @description * Directive that instantiates * {@link ng.directive:form.FormController FormController}. * * If `name` attribute is specified, the form controller is published onto the current scope under * this name. * * # Alias: {@link ng.directive:ngForm `ngForm`} * * In angular forms can be nested. This means that the outer form is valid when all of the child * forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this * reason angular provides {@link ng.directive:ngForm `ngForm`} alias * which behaves identical to `<form>` but allows form nesting. * * * # CSS classes * - `ng-valid` Is set if the form is valid. * - `ng-invalid` Is set if the form is invalid. * - `ng-pristine` Is set if the form is pristine. * - `ng-dirty` Is set if the form is dirty. * * * # Submitting a form and preventing default action * * Since the role of forms in client-side Angular applications is different than in classical * roundtrip apps, it is desirable for the browser not to translate the form submission into a full * page reload that sends the data to the server. Instead some javascript logic should be triggered * to handle the form submission in application specific way. * * For this reason, Angular prevents the default action (form submission to the server) unless the * `<form>` element has an `action` attribute specified. * * You can use one of the following two ways to specify what javascript method should be called when * a form is submitted: * * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element * - {@link ng.directive:ngClick ngClick} directive on the first * button or input field of type submit (input[type=submit]) * * To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This * is because of the following form submission rules coming from the html spec: * * - If a form has only one input field then hitting enter in this field triggers form submit * (`ngSubmit`) * - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter * doesn't trigger submit * - if a form has one or more input fields and one or more buttons or input[type=submit] then * hitting enter in any of the input fields will trigger the click handler on the *first* button or * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) * * @param {string=} name Name of the form. If specified, the form controller will be published into * related scope, under this name. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.userType = 'guest'; } </script> <form name="myForm" ng-controller="Ctrl"> userType: <input name="input" ng-model="userType" required> <span class="error" ng-show="myForm.input.$error.required">Required!</span><br> <tt>userType = {{userType}}</tt><br> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('userType')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('userType').enter(''); expect(binding('userType')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var formDirectiveFactory = function(isNgForm) { return ['$timeout', function($timeout) { var formDirective = { name: 'form', restrict: 'E', controller: FormController, compile: function() { return { pre: function(scope, formElement, attr, controller) { if (!attr.action) { // we can't use jq events because if a form is destroyed during submission the default // action is not prevented. see #1238 // // IE 9 is not affected because it doesn't fire a submit event and try to do a full // page reload if the form was destroyed by submission of the form via a click handler // on a button in the form. Looks like an IE9 specific bug. var preventDefaultListener = function(event) { event.preventDefault ? event.preventDefault() : event.returnValue = false; // IE }; addEventListenerFn(formElement[0], 'submit', preventDefaultListener); // unregister the preventDefault listener so that we don't not leak memory but in a // way that will achieve the prevention of the default action. formElement.bind('$destroy', function() { $timeout(function() { removeEventListenerFn(formElement[0], 'submit', preventDefaultListener); }, 0, false); }); } var parentFormCtrl = formElement.parent().controller('form'), alias = attr.name || attr.ngForm; if (alias) { scope[alias] = controller; } if (parentFormCtrl) { formElement.bind('$destroy', function() { parentFormCtrl.$removeControl(controller); if (alias) { scope[alias] = undefined; } extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards }); } } }; } }; return isNgForm ? extend(copy(formDirective), {restrict: 'EAC'}) : formDirective; }]; }; var formDirective = formDirectiveFactory(); var ngFormDirective = formDirectiveFactory(true); var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/; var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; var inputType = { /** * @ngdoc inputType * @name ng.directive:input.text * * @description * Standard HTML text input with angular data binding. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Adds `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trimming the * input. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'guest'; $scope.word = /^\s*\w*\s*$/; } </script> <form name="myForm" ng-controller="Ctrl"> Single word: <input type="text" name="input" ng-model="text" ng-pattern="word" required ng-trim="false"> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.pattern"> Single word only!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if multi word', function() { input('text').enter('hello world'); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should not be trimmed', function() { input('text').enter('untrimmed '); expect(binding('text')).toEqual('untrimmed '); expect(binding('myForm.input.$valid')).toEqual('true'); }); </doc:scenario> </doc:example> */ 'text': textInputType, /** * @ngdoc inputType * @name ng.directive:input.number * * @description * Text input with number validation and transformation. Sets the `number` validation * error if not a valid number. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value = 12; } </script> <form name="myForm" ng-controller="Ctrl"> Number: <input type="number" name="input" ng-model="value" min="0" max="99" required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <span class="error" ng-show="myForm.list.$error.number"> Not valid number!</span> <tt>value = {{value}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('value')).toEqual('12'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('value').enter(''); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if over max', function() { input('value').enter('123'); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'number': numberInputType, /** * @ngdoc inputType * @name ng.directive:input.url * * @description * Text input with URL validation. Sets the `url` validation error key if the content is not a * valid URL. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'http://google.com'; } </script> <form name="myForm" ng-controller="Ctrl"> URL: <input type="url" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.url"> Not valid url!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('http://google.com'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not url', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'url': urlInputType, /** * @ngdoc inputType * @name ng.directive:input.email * * @description * Text input with email validation. Sets the `email` validation error key if not a valid email * address. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'me@example.com'; } </script> <form name="myForm" ng-controller="Ctrl"> Email: <input type="email" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.email"> Not valid email!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('me@example.com'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not email', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'email': emailInputType, /** * @ngdoc inputType * @name ng.directive:input.radio * * @description * HTML radio button. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string} value The value to which the expression should be set when selected. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.color = 'blue'; } </script> <form name="myForm" ng-controller="Ctrl"> <input type="radio" ng-model="color" value="red"> Red <br/> <input type="radio" ng-model="color" value="green"> Green <br/> <input type="radio" ng-model="color" value="blue"> Blue <br/> <tt>color = {{color}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('color')).toEqual('blue'); input('color').select('red'); expect(binding('color')).toEqual('red'); }); </doc:scenario> </doc:example> */ 'radio': radioInputType, /** * @ngdoc inputType * @name ng.directive:input.checkbox * * @description * HTML checkbox. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngTrueValue The value to which the expression should be set when selected. * @param {string=} ngFalseValue The value to which the expression should be set when not selected. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value1 = true; $scope.value2 = 'YES' } </script> <form name="myForm" ng-controller="Ctrl"> Value1: <input type="checkbox" ng-model="value1"> <br/> Value2: <input type="checkbox" ng-model="value2" ng-true-value="YES" ng-false-value="NO"> <br/> <tt>value1 = {{value1}}</tt><br/> <tt>value2 = {{value2}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('value1')).toEqual('true'); expect(binding('value2')).toEqual('YES'); input('value1').check(); input('value2').check(); expect(binding('value1')).toEqual('false'); expect(binding('value2')).toEqual('NO'); }); </doc:scenario> </doc:example> */ 'checkbox': checkboxInputType, 'hidden': noop, 'button': noop, 'submit': noop, 'reset': noop }; function isEmpty(value) { return isUndefined(value) || value === '' || value === null || value !== value; } function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { var listener = function() { var value = element.val(); // By default we will trim the value // If the attribute ng-trim exists we will avoid trimming // e.g. <input ng-model="foo" ng-trim="false"> if (toBoolean(attr.ngTrim || 'T')) { value = trim(value); } if (ctrl.$viewValue !== value) { scope.$apply(function() { ctrl.$setViewValue(value); }); } }; // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the // input event on backspace, delete or cut if ($sniffer.hasEvent('input')) { element.bind('input', listener); } else { var timeout; var deferListener = function() { if (!timeout) { timeout = $browser.defer(function() { listener(); timeout = null; }); } }; element.bind('keydown', function(event) { var key = event.keyCode; // ignore // command modifiers arrows if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; deferListener(); }); // if user paste into input using mouse, we need "change" event to catch it element.bind('change', listener); // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it if ($sniffer.hasEvent('paste')) { element.bind('paste cut', deferListener); } } ctrl.$render = function() { element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); }; // pattern validator var pattern = attr.ngPattern, patternValidator, match; var validate = function(regexp, value) { if (isEmpty(value) || regexp.test(value)) { ctrl.$setValidity('pattern', true); return value; } else { ctrl.$setValidity('pattern', false); return undefined; } }; if (pattern) { match = pattern.match(/^\/(.*)\/([gim]*)$/); if (match) { pattern = new RegExp(match[1], match[2]); patternValidator = function(value) { return validate(pattern, value) }; } else { patternValidator = function(value) { var patternObj = scope.$eval(pattern); if (!patternObj || !patternObj.test) { throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj); } return validate(patternObj, value); }; } ctrl.$formatters.push(patternValidator); ctrl.$parsers.push(patternValidator); } // min length validator if (attr.ngMinlength) { var minlength = int(attr.ngMinlength); var minLengthValidator = function(value) { if (!isEmpty(value) && value.length < minlength) { ctrl.$setValidity('minlength', false); return undefined; } else { ctrl.$setValidity('minlength', true); return value; } }; ctrl.$parsers.push(minLengthValidator); ctrl.$formatters.push(minLengthValidator); } // max length validator if (attr.ngMaxlength) { var maxlength = int(attr.ngMaxlength); var maxLengthValidator = function(value) { if (!isEmpty(value) && value.length > maxlength) { ctrl.$setValidity('maxlength', false); return undefined; } else { ctrl.$setValidity('maxlength', true); return value; } }; ctrl.$parsers.push(maxLengthValidator); ctrl.$formatters.push(maxLengthValidator); } } function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); ctrl.$parsers.push(function(value) { var empty = isEmpty(value); if (empty || NUMBER_REGEXP.test(value)) { ctrl.$setValidity('number', true); return value === '' ? null : (empty ? value : parseFloat(value)); } else { ctrl.$setValidity('number', false); return undefined; } }); ctrl.$formatters.push(function(value) { return isEmpty(value) ? '' : '' + value; }); if (attr.min) { var min = parseFloat(attr.min); var minValidator = function(value) { if (!isEmpty(value) && value < min) { ctrl.$setValidity('min', false); return undefined; } else { ctrl.$setValidity('min', true); return value; } }; ctrl.$parsers.push(minValidator); ctrl.$formatters.push(minValidator); } if (attr.max) { var max = parseFloat(attr.max); var maxValidator = function(value) { if (!isEmpty(value) && value > max) { ctrl.$setValidity('max', false); return undefined; } else { ctrl.$setValidity('max', true); return value; } }; ctrl.$parsers.push(maxValidator); ctrl.$formatters.push(maxValidator); } ctrl.$formatters.push(function(value) { if (isEmpty(value) || isNumber(value)) { ctrl.$setValidity('number', true); return value; } else { ctrl.$setValidity('number', false); return undefined; } }); } function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var urlValidator = function(value) { if (isEmpty(value) || URL_REGEXP.test(value)) { ctrl.$setValidity('url', true); return value; } else { ctrl.$setValidity('url', false); return undefined; } }; ctrl.$formatters.push(urlValidator); ctrl.$parsers.push(urlValidator); } function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var emailValidator = function(value) { if (isEmpty(value) || EMAIL_REGEXP.test(value)) { ctrl.$setValidity('email', true); return value; } else { ctrl.$setValidity('email', false); return undefined; } }; ctrl.$formatters.push(emailValidator); ctrl.$parsers.push(emailValidator); } function radioInputType(scope, element, attr, ctrl) { // make the name unique, if not defined if (isUndefined(attr.name)) { element.attr('name', nextUid()); } element.bind('click', function() { if (element[0].checked) { scope.$apply(function() { ctrl.$setViewValue(attr.value); }); } }); ctrl.$render = function() { var value = attr.value; element[0].checked = (value == ctrl.$viewValue); }; attr.$observe('value', ctrl.$render); } function checkboxInputType(scope, element, attr, ctrl) { var trueValue = attr.ngTrueValue, falseValue = attr.ngFalseValue; if (!isString(trueValue)) trueValue = true; if (!isString(falseValue)) falseValue = false; element.bind('click', function() { scope.$apply(function() { ctrl.$setViewValue(element[0].checked); }); }); ctrl.$render = function() { element[0].checked = ctrl.$viewValue; }; ctrl.$formatters.push(function(value) { return value === trueValue; }); ctrl.$parsers.push(function(value) { return value ? trueValue : falseValue; }); } /** * @ngdoc directive * @name ng.directive:textarea * @restrict E * * @description * HTML textarea element control with angular data-binding. The data-binding and validation * properties of this element are exactly the same as those of the * {@link ng.directive:input input element}. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. */ /** * @ngdoc directive * @name ng.directive:input * @restrict E * * @description * HTML input element control with angular data-binding. Input control follows HTML5 input types * and polyfills the HTML5 validation behavior for older browsers. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {boolean=} ngRequired Sets `required` attribute if set to true * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.user = {name: 'guest', last: 'visitor'}; } </script> <div ng-controller="Ctrl"> <form name="myForm"> User name: <input type="text" name="userName" ng-model="user.name" required> <span class="error" ng-show="myForm.userName.$error.required"> Required!</span><br> Last name: <input type="text" name="lastName" ng-model="user.last" ng-minlength="3" ng-maxlength="10"> <span class="error" ng-show="myForm.lastName.$error.minlength"> Too short!</span> <span class="error" ng-show="myForm.lastName.$error.maxlength"> Too long!</span><br> </form> <hr> <tt>user = {{user}}</tt><br/> <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br> <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br> <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br> <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if empty when required', function() { input('user.name').enter(''); expect(binding('user')).toEqual('{"last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('false'); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be valid if empty when min length is set', function() { input('user.last').enter(''); expect(binding('user')).toEqual('{"name":"guest","last":""}'); expect(binding('myForm.lastName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if less than required min length', function() { input('user.last').enter('xx'); expect(binding('user')).toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/minlength/); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be invalid if longer than max length', function() { input('user.last').enter('some ridiculously long name'); expect(binding('user')) .toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/maxlength/); expect(binding('myForm.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) { return { restrict: 'E', require: '?ngModel', link: function(scope, element, attr, ctrl) { if (ctrl) { (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer, $browser); } } }; }]; var VALID_CLASS = 'ng-valid', INVALID_CLASS = 'ng-invalid', PRISTINE_CLASS = 'ng-pristine', DIRTY_CLASS = 'ng-dirty'; /** * @ngdoc object * @name ng.directive:ngModel.NgModelController * * @property {string} $viewValue Actual string value in the view. * @property {*} $modelValue The value in the model, that the control is bound to. * @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes * all of these functions to sanitize / convert the value as well as validate. * * @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of * these functions to convert the value as well as validate. * * @property {Object} $error An object hash with all errors as keys. * * @property {boolean} $pristine True if user has not interacted with the control yet. * @property {boolean} $dirty True if user has already interacted with the control. * @property {boolean} $valid True if there is no error. * @property {boolean} $invalid True if at least one error on the control. * * @description * * `NgModelController` provides API for the `ng-model` directive. The controller contains * services for data-binding, validation, CSS update, value formatting and parsing. It * specifically does not contain any logic which deals with DOM rendering or listening to * DOM events. The `NgModelController` is meant to be extended by other directives where, the * directive provides DOM manipulation and the `NgModelController` provides the data-binding. * * This example shows how to use `NgModelController` with a custom control to achieve * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) * collaborate together to achieve the desired result. * * <example module="customControl"> <file name="style.css"> [contenteditable] { border: 1px solid black; background-color: white; min-height: 20px; } .ng-invalid { border: 1px solid red; } </file> <file name="script.js"> angular.module('customControl', []). directive('contenteditable', function() { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, element, attrs, ngModel) { if(!ngModel) return; // do nothing if no ng-model // Specify how UI should be updated ngModel.$render = function() { element.html(ngModel.$viewValue || ''); }; // Listen for change events to enable binding element.bind('blur keyup change', function() { scope.$apply(read); }); read(); // initialize // Write data to the model function read() { ngModel.$setViewValue(element.html()); } } }; }); </file> <file name="index.html"> <form name="myForm"> <div contenteditable name="myWidget" ng-model="userContent" required>Change me!</div> <span ng-show="myForm.myWidget.$error.required">Required!</span> <hr> <textarea ng-model="userContent"></textarea> </form> </file> <file name="scenario.js"> it('should data-bind and become invalid', function() { var contentEditable = element('[contenteditable]'); expect(contentEditable.text()).toEqual('Change me!'); input('userContent').enter(''); expect(contentEditable.text()).toEqual(''); expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/); }); </file> * </example> * */ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', function($scope, $exceptionHandler, $attr, $element, $parse) { this.$viewValue = Number.NaN; this.$modelValue = Number.NaN; this.$parsers = []; this.$formatters = []; this.$viewChangeListeners = []; this.$pristine = true; this.$dirty = false; this.$valid = true; this.$invalid = false; this.$name = $attr.name; var ngModelGet = $parse($attr.ngModel), ngModelSet = ngModelGet.assign; if (!ngModelSet) { throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel + ' (' + startingTag($element) + ')'); } /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$render * @methodOf ng.directive:ngModel.NgModelController * * @description * Called when the view needs to be updated. It is expected that the user of the ng-model * directive will implement this method. */ this.$render = noop; var parentForm = $element.inheritedData('$formController') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid $error = this.$error = {}; // keep invalid keys here // Setup initial state of the control $element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; $element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$setValidity * @methodOf ng.directive:ngModel.NgModelController * * @description * Change the validity state, and notifies the form when the control changes validity. (i.e. it * does not notify form if given validator is already marked as invalid). * * This method should be called by validators - i.e. the parser or formatter functions. * * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. * The `validationErrorKey` should be in camelCase and will get converted into dash-case * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` * class and can be bound to as `{{someForm.someControl.$error.myError}}` . * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). */ this.$setValidity = function(validationErrorKey, isValid) { if ($error[validationErrorKey] === !isValid) return; if (isValid) { if ($error[validationErrorKey]) invalidCount--; if (!invalidCount) { toggleValidCss(true); this.$valid = true; this.$invalid = false; } } else { toggleValidCss(false); this.$invalid = true; this.$valid = false; invalidCount++; } $error[validationErrorKey] = !isValid; toggleValidCss(isValid, validationErrorKey); parentForm.$setValidity(validationErrorKey, isValid, this); }; /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$setPristine * @methodOf ng.directive:ngModel.NgModelController * * @description * Sets the control to its pristine state. * * This method can be called to remove the 'ng-dirty' class and set the control to its pristine * state (ng-pristine class). */ this.$setPristine = function () { this.$dirty = false; this.$pristine = true; $element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); }; /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$setViewValue * @methodOf ng.directive:ngModel.NgModelController * * @description * Read a value from view. * * This method should be called from within a DOM event handler. * For example {@link ng.directive:input input} or * {@link ng.directive:select select} directives call it. * * It internally calls all `parsers` and if resulted value is valid, updates the model and * calls all registered change listeners. * * @param {string} value Value from the view. */ this.$setViewValue = function(value) { this.$viewValue = value; // change to dirty if (this.$pristine) { this.$dirty = true; this.$pristine = false; $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); parentForm.$setDirty(); } forEach(this.$parsers, function(fn) { value = fn(value); }); if (this.$modelValue !== value) { this.$modelValue = value; ngModelSet($scope, value); forEach(this.$viewChangeListeners, function(listener) { try { listener(); } catch(e) { $exceptionHandler(e); } }) } }; // model -> value var ctrl = this; $scope.$watch(function ngModelWatch() { var value = ngModelGet($scope); // if scope model value and ngModel value are out of sync if (ctrl.$modelValue !== value) { var formatters = ctrl.$formatters, idx = formatters.length; ctrl.$modelValue = value; while(idx--) { value = formatters[idx](value); } if (ctrl.$viewValue !== value) { ctrl.$viewValue = value; ctrl.$render(); } } }); }]; /** * @ngdoc directive * @name ng.directive:ngModel * * @element input * * @description * Is directive that tells Angular to do two-way data binding. It works together with `input`, * `select`, `textarea`. You can easily write your own directives to use `ngModel` as well. * * `ngModel` is responsible for: * * - binding the view into the model, which other directives such as `input`, `textarea` or `select` * require, * - providing validation behavior (i.e. required, number, email, url), * - keeping state of the control (valid/invalid, dirty/pristine, validation errors), * - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`), * - register the control with parent {@link ng.directive:form form}. * * For basic examples, how to use `ngModel`, see: * * - {@link ng.directive:input input} * - {@link ng.directive:input.text text} * - {@link ng.directive:input.checkbox checkbox} * - {@link ng.directive:input.radio radio} * - {@link ng.directive:input.number number} * - {@link ng.directive:input.email email} * - {@link ng.directive:input.url url} * - {@link ng.directive:select select} * - {@link ng.directive:textarea textarea} * */ var ngModelDirective = function() { return { require: ['ngModel', '^?form'], controller: NgModelController, link: function(scope, element, attr, ctrls) { // notify others, especially parent forms var modelCtrl = ctrls[0], formCtrl = ctrls[1] || nullFormCtrl; formCtrl.$addControl(modelCtrl); element.bind('$destroy', function() { formCtrl.$removeControl(modelCtrl); }); } }; }; /** * @ngdoc directive * @name ng.directive:ngChange * @restrict E * * @description * Evaluate given expression when user changes the input. * The expression is not evaluated when the value change is coming from the model. * * Note, this directive requires `ngModel` to be present. * * @element input * * @example * <doc:example> * <doc:source> * <script> * function Controller($scope) { * $scope.counter = 0; * $scope.change = function() { * $scope.counter++; * }; * } * </script> * <div ng-controller="Controller"> * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" /> * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" /> * <label for="ng-change-example2">Confirmed</label><br /> * debug = {{confirmed}}<br /> * counter = {{counter}} * </div> * </doc:source> * <doc:scenario> * it('should evaluate the expression if changing from view', function() { * expect(binding('counter')).toEqual('0'); * element('#ng-change-example1').click(); * expect(binding('counter')).toEqual('1'); * expect(binding('confirmed')).toEqual('true'); * }); * * it('should not evaluate the expression if changing from model', function() { * element('#ng-change-example2').click(); * expect(binding('counter')).toEqual('0'); * expect(binding('confirmed')).toEqual('true'); * }); * </doc:scenario> * </doc:example> */ var ngChangeDirective = valueFn({ require: 'ngModel', link: function(scope, element, attr, ctrl) { ctrl.$viewChangeListeners.push(function() { scope.$eval(attr.ngChange); }); } }); var requiredDirective = function() { return { require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; attr.required = true; // force truthy in case we are on non input element var validator = function(value) { if (attr.required && (isEmpty(value) || value === false)) { ctrl.$setValidity('required', false); return; } else { ctrl.$setValidity('required', true); return value; } }; ctrl.$formatters.push(validator); ctrl.$parsers.unshift(validator); attr.$observe('required', function() { validator(ctrl.$viewValue); }); } }; }; /** * @ngdoc directive * @name ng.directive:ngList * * @description * Text input that converts between comma-separated string into an array of strings. * * @element input * @param {string=} ngList optional delimiter that should be used to split the value. If * specified in form `/something/` then the value will be converted into a regular expression. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.names = ['igor', 'misko', 'vojta']; } </script> <form name="myForm" ng-controller="Ctrl"> List: <input name="namesInput" ng-model="names" ng-list required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <tt>names = {{names}}</tt><br/> <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('names')).toEqual('["igor","misko","vojta"]'); expect(binding('myForm.namesInput.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('names').enter(''); expect(binding('names')).toEqual('[]'); expect(binding('myForm.namesInput.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var ngListDirective = function() { return { require: 'ngModel', link: function(scope, element, attr, ctrl) { var match = /\/(.*)\//.exec(attr.ngList), separator = match && new RegExp(match[1]) || attr.ngList || ','; var parse = function(viewValue) { var list = []; if (viewValue) { forEach(viewValue.split(separator), function(value) { if (value) list.push(trim(value)); }); } return list; }; ctrl.$parsers.push(parse); ctrl.$formatters.push(function(value) { if (isArray(value)) { return value.join(', '); } return undefined; }); } }; }; var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; var ngValueDirective = function() { return { priority: 100, compile: function(tpl, tplAttr) { if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { return function(scope, elm, attr) { attr.$set('value', scope.$eval(attr.ngValue)); }; } else { return function(scope, elm, attr) { scope.$watch(attr.ngValue, function valueWatchAction(value) { attr.$set('value', value, false); }); }; } } }; }; /** * @ngdoc directive * @name ng.directive:ngBind * * @description * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element * with the value of a given expression, and to update the text content when the value of that * expression changes. * * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like * `{{ expression }}` which is similar but less verbose. * * One scenario in which the use of `ngBind` is preferred over `{{ expression }}` binding is when * it's desirable to put bindings into template that is momentarily displayed by the browser in its * raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the * bindings invisible to the user while the page is loading. * * An alternative solution to this problem would be using the * {@link ng.directive:ngCloak ngCloak} directive. * * * @element ANY * @param {expression} ngBind {@link guide/expression Expression} to evaluate. * * @example * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.name = 'Whirled'; } </script> <div ng-controller="Ctrl"> Enter name: <input type="text" ng-model="name"><br> Hello <span ng-bind="name"></span>! </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('name')).toBe('Whirled'); using('.doc-example-live').input('name').enter('world'); expect(using('.doc-example-live').binding('name')).toBe('world'); }); </doc:scenario> </doc:example> */ var ngBindDirective = ngDirective(function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBind); scope.$watch(attr.ngBind, function ngBindWatchAction(value) { element.text(value == undefined ? '' : value); }); }); /** * @ngdoc directive * @name ng.directive:ngBindTemplate * * @description * The `ngBindTemplate` directive specifies that the element * text should be replaced with the template in ngBindTemplate. * Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}` * expressions. (This is required since some HTML elements * can not have SPAN elements such as TITLE, or OPTION to name a few.) * * @element ANY * @param {string} ngBindTemplate template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.salutation = 'Hello'; $scope.name = 'World'; } </script> <div ng-controller="Ctrl"> Salutation: <input type="text" ng-model="salutation"><br> Name: <input type="text" ng-model="name"><br> <pre ng-bind-template="{{salutation}} {{name}}!"></pre> </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('salutation')). toBe('Hello'); expect(using('.doc-example-live').binding('name')). toBe('World'); using('.doc-example-live').input('salutation').enter('Greetings'); using('.doc-example-live').input('name').enter('user'); expect(using('.doc-example-live').binding('salutation')). toBe('Greetings'); expect(using('.doc-example-live').binding('name')). toBe('user'); }); </doc:scenario> </doc:example> */ var ngBindTemplateDirective = ['$interpolate', function($interpolate) { return function(scope, element, attr) { // TODO: move this to scenario runner var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); element.addClass('ng-binding').data('$binding', interpolateFn); attr.$observe('ngBindTemplate', function(value) { element.text(value); }); } }]; /** * @ngdoc directive * @name ng.directive:ngBindHtmlUnsafe * * @description * Creates a binding that will innerHTML the result of evaluating the `expression` into the current * element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if * {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too * restrictive and when you absolutely trust the source of the content you are binding to. * * See {@link ngSanitize.$sanitize $sanitize} docs for examples. * * @element ANY * @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate. */ var ngBindHtmlUnsafeDirective = [function() { return function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe); scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) { element.html(value || ''); }); }; }]; function classDirective(name, selector) { name = 'ngClass' + name; return ngDirective(function(scope, element, attr) { var oldVal = undefined; scope.$watch(attr[name], ngClassWatchAction, true); attr.$observe('class', function(value) { var ngClass = scope.$eval(attr[name]); ngClassWatchAction(ngClass, ngClass); }); if (name !== 'ngClass') { scope.$watch('$index', function($index, old$index) { var mod = $index & 1; if (mod !== old$index & 1) { if (mod === selector) { addClass(scope.$eval(attr[name])); } else { removeClass(scope.$eval(attr[name])); } } }); } function ngClassWatchAction(newVal) { if (selector === true || scope.$index % 2 === selector) { if (oldVal && !equals(newVal,oldVal)) { removeClass(oldVal); } addClass(newVal); } oldVal = copy(newVal); } function removeClass(classVal) { if (isObject(classVal) && !isArray(classVal)) { classVal = map(classVal, function(v, k) { if (v) return k }); } element.removeClass(isArray(classVal) ? classVal.join(' ') : classVal); } function addClass(classVal) { if (isObject(classVal) && !isArray(classVal)) { classVal = map(classVal, function(v, k) { if (v) return k }); } if (classVal) { element.addClass(isArray(classVal) ? classVal.join(' ') : classVal); } } }); } /** * @ngdoc directive * @name ng.directive:ngClass * * @description * The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an * expression that represents all classes to be added. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the * new classes are added. * * @element ANY * @param {expression} ngClass {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class * names, an array, or a map of class names to boolean values. * * @example <example> <file name="index.html"> <input type="button" value="set" ng-click="myVar='my-class'"> <input type="button" value="clear" ng-click="myVar=''"> <br> <span ng-class="myVar">Sample Text</span> </file> <file name="style.css"> .my-class { color: red; } </file> <file name="scenario.js"> it('should check ng-class', function() { expect(element('.doc-example-live span').prop('className')).not(). toMatch(/my-class/); using('.doc-example-live').element(':button:first').click(); expect(element('.doc-example-live span').prop('className')). toMatch(/my-class/); using('.doc-example-live').element(':button:last').click(); expect(element('.doc-example-live span').prop('className')).not(). toMatch(/my-class/); }); </file> </example> */ var ngClassDirective = classDirective('', true); /** * @ngdoc directive * @name ng.directive:ngClassOdd * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link ng.directive:ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="scenario.js"> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/odd/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/even/); }); </file> </example> */ var ngClassOddDirective = classDirective('Odd', 0); /** * @ngdoc directive * @name ng.directive:ngClassEven * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link ng.directive:ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The * result of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="scenario.js"> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/odd/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/even/); }); </file> </example> */ var ngClassEvenDirective = classDirective('Even', 1); /** * @ngdoc directive * @name ng.directive:ngCloak * * @description * The `ngCloak` directive is used to prevent the Angular html template from being briefly * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this * directive to avoid the undesirable flicker effect caused by the html template display. * * The directive can be applied to the `<body>` element, but typically a fine-grained application is * preferred in order to benefit from progressive rendering of the browser view. * * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and * `angular.min.js` files. Following is the css rule: * * <pre> * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { * display: none; * } * </pre> * * When this css rule is loaded by the browser, all html elements (including their children) that * are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive * during the compilation of the template it deletes the `ngCloak` element attribute, which * makes the compiled element visible. * * For the best result, `angular.js` script must be loaded in the head section of the html file; * alternatively, the css rule (above) must be included in the external stylesheet of the * application. * * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css * class `ngCloak` in addition to `ngCloak` directive as shown in the example below. * * @element ANY * * @example <doc:example> <doc:source> <div id="template1" ng-cloak>{{ 'hello' }}</div> <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div> </doc:source> <doc:scenario> it('should remove the template directive and css class', function() { expect(element('.doc-example-live #template1').attr('ng-cloak')). not().toBeDefined(); expect(element('.doc-example-live #template2').attr('ng-cloak')). not().toBeDefined(); }); </doc:scenario> </doc:example> * */ var ngCloakDirective = ngDirective({ compile: function(element, attr) { attr.$set('ngCloak', undefined); element.removeClass('ng-cloak'); } }); /** * @ngdoc directive * @name ng.directive:ngController * * @description * The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — The Model is data in scope properties; scopes are attached to the DOM. * * View — The template (HTML with data bindings) is rendered into the View. * * Controller — The `ngController` directive specifies a Controller class; the class has * methods that typically express the business logic behind the application. * * Note that an alternative way to define controllers is via the {@link ng.$route $route} service. * * @element ANY * @scope * @param {expression} ngController Name of a globally accessible constructor function or an * {@link guide/expression expression} that on the current scope evaluates to a * constructor function. The controller instance can further be published into the scope * by adding `as localName` the controller name attribute. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Notice that the scope becomes the `this` for the * controller's instance. This allows for easy access to the view data from the controller. Also * notice that any changes to the data are automatically reflected in the View without the need * for a manual update. The example is included in two different declaration styles based on * your style preferences. <doc:example> <doc:source> <script> function SettingsController() { this.name = "John Smith"; this.contacts = [ {type: 'phone', value: '408 555 1212'}, {type: 'email', value: 'john.smith@example.org'} ]; }; SettingsController.prototype.greet = function() { alert(this.name); }; SettingsController.prototype.addContact = function() { this.contacts.push({type: 'email', value: 'yourname@example.org'}); }; SettingsController.prototype.removeContact = function(contactToRemove) { var index = this.contacts.indexOf(contactToRemove); this.contacts.splice(index, 1); }; SettingsController.prototype.clearContact = function(contact) { contact.type = 'phone'; contact.value = ''; }; </script> <div ng-controller="SettingsController as settings"> Name: <input type="text" ng-model="settings.name"/> [ <a href="" ng-click="settings.greet()">greet</a> ]<br/> Contact: <ul> <li ng-repeat="contact in settings.contacts"> <select ng-model="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" ng-model="contact.value"/> [ <a href="" ng-click="settings.clearContact(contact)">clear</a> | <a href="" ng-click="settings.removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li> </ul> </div> </doc:source> <doc:scenario> it('should check controller', function() { expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li:nth-child(1) input').val()) .toBe('408 555 1212'); expect(element('.doc-example-live li:nth-child(2) input').val()) .toBe('john.smith@example.org'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li:nth-child(3) input').val()) .toBe('yourname@example.org'); }); </doc:scenario> </doc:example> <doc:example> <doc:source> <script> function SettingsController($scope) { $scope.name = "John Smith"; $scope.contacts = [ {type:'phone', value:'408 555 1212'}, {type:'email', value:'john.smith@example.org'} ]; $scope.greet = function() { alert(this.name); }; $scope.addContact = function() { this.contacts.push({type:'email', value:'yourname@example.org'}); }; $scope.removeContact = function(contactToRemove) { var index = this.contacts.indexOf(contactToRemove); this.contacts.splice(index, 1); }; $scope.clearContact = function(contact) { contact.type = 'phone'; contact.value = ''; }; } </script> <div ng-controller="SettingsController"> Name: <input type="text" ng-model="name"/> [ <a href="" ng-click="greet()">greet</a> ]<br/> Contact: <ul> <li ng-repeat="contact in contacts"> <select ng-model="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" ng-model="contact.value"/> [ <a href="" ng-click="clearContact(contact)">clear</a> | <a href="" ng-click="removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng-click="addContact()">add</a> ]</li> </ul> </div> </doc:source> <doc:scenario> it('should check controller', function() { expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li:nth-child(1) input').val()) .toBe('408 555 1212'); expect(element('.doc-example-live li:nth-child(2) input').val()) .toBe('john.smith@example.org'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li:nth-child(3) input').val()) .toBe('yourname@example.org'); }); </doc:scenario> </doc:example> */ var ngControllerDirective = [function() { return { scope: true, controller: '@' }; }]; /** * @ngdoc directive * @name ng.directive:ngCsp * @priority 1000 * * @element html * @description * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. * * This is necessary when developing things like Google Chrome Extensions. * * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). * For us to be compatible, we just need to implement the "getterFn" in $parse without violating * any of these restrictions. * * AngularJS uses `Function(string)` generated functions as a speed optimization. By applying `ngCsp` * it is be possible to opt into the CSP compatible mode. When this mode is on AngularJS will * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will * be raised. * * In order to use this feature put `ngCsp` directive on the root element of the application. * * @example * This example shows how to apply the `ngCsp` directive to the `html` tag. <pre> <!doctype html> <html ng-app ng-csp> ... ... </html> </pre> */ var ngCspDirective = ['$sniffer', function($sniffer) { return { priority: 1000, compile: function() { $sniffer.csp = true; } }; }]; /** * @ngdoc directive * @name ng.directive:ngClick * * @description * The ngClick allows you to specify custom behavior when * element is clicked. * * @element ANY * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon * click. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-click="count = count + 1" ng-init="count=0"> Increment </button> count: {{count}} </doc:source> <doc:scenario> it('should check ng-click', function() { expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); </doc:scenario> </doc:example> */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. */ var ngEventDirectives = {}; forEach( 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress'.split(' '), function(name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function($parse) { return function(scope, element, attr) { var fn = $parse(attr[directiveName]); element.bind(lowercase(name), function(event) { scope.$apply(function() { fn(scope, {$event:event}); }); }); }; }]; } ); /** * @ngdoc directive * @name ng.directive:ngDblclick * * @description * The `ngDblclick` directive allows you to specify custom behavior on dblclick event. * * @element ANY * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon * dblclick. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMousedown * * @description * The ngMousedown directive allows you to specify custom behavior on mousedown event. * * @element ANY * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon * mousedown. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseup * * @description * Specify custom behavior on mouseup event. * * @element ANY * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon * mouseup. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseover * * @description * Specify custom behavior on mouseover event. * * @element ANY * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon * mouseover. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseenter * * @description * Specify custom behavior on mouseenter event. * * @element ANY * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon * mouseenter. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseleave * * @description * Specify custom behavior on mouseleave event. * * @element ANY * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon * mouseleave. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMousemove * * @description * Specify custom behavior on mousemove event. * * @element ANY * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon * mousemove. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngKeydown * * @description * Specify custom behavior on keydown event. * * @element ANY * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngKeyup * * @description * Specify custom behavior on keyup event. * * @element ANY * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngKeypress * * @description * Specify custom behavior on keypress event. * * @element ANY * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon * keypress. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngSubmit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page). * * @element form * @param {expression} ngSubmit {@link guide/expression Expression} to eval. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.list = []; $scope.text = 'hello'; $scope.submit = function() { if (this.text) { this.list.push(this.text); this.text = ''; } }; } </script> <form ng-submit="submit()" ng-controller="Ctrl"> Enter text and hit enter: <input type="text" ng-model="text" name="text" /> <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre> </form> </doc:source> <doc:scenario> it('should check ng-submit', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); expect(input('text').val()).toBe(''); }); it('should ignore empty strings', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); }); </doc:scenario> </doc:example> */ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { element.bind('submit', function() { scope.$apply(attrs.ngSubmit); }); }); /** * @ngdoc directive * @name ng.directive:ngIf * @restrict A * * @description * The `ngIf` directive removes and recreates a portion of the DOM tree (HTML) * conditionally based on **"falsy"** and **"truthy"** values, respectively, evaluated within * an {expression}. In other words, if the expression assigned to **ngIf evaluates to a false * value** then **the element is removed from the DOM** and **if true** then **a clone of the * element is reinserted into the DOM**. * * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the * element in the DOM rather than changing its visibility via the `display` css property. A common * case when this difference is significant is when using css selectors that rely on an element's * position within the DOM (HTML), such as the `:first-child` or `:last-child` pseudo-classes. * * Note that **when an element is removed using ngIf its scope is destroyed** and **a new scope * is created when the element is restored**. The scope created within `ngIf` inherits from * its parent scope using * {@link https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance prototypal inheritance}. * An important implication of this is if `ngModel` is used within `ngIf` to bind to * a javascript primitive defined in the parent scope. In this case any modifications made to the * variable within the child scope will override (hide) the value in the parent scope. * * Also, `ngIf` recreates elements using their compiled state. An example scenario of this behavior * is if an element's class attribute is directly modified after it's compiled, using something like * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element * the added class will be lost because the original compiled state is used to regenerate the element. * * Additionally, you can provide animations via the ngAnimate attribute to animate the **enter** * and **leave** effects. * * @animations * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container * leave - happens just before the ngIf contents are removed from the DOM * * @element ANY * @scope * @param {expression} ngIf If the {@link guide/expression expression} is falsy then * the element is removed from the DOM tree (HTML). * * @example <example animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/> Show when checked: <span ng-if="checked" ng-animate="'example'"> I'm removed when the checkbox is unchecked. </span> </file> <file name="animations.css"> .example-leave, .example-enter { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -ms-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; } .example-enter { opacity:0; } .example-enter.example-enter-active { opacity:1; } .example-leave { opacity:1; } .example-leave.example-leave-active { opacity:0; } </file> </example> */ var ngIfDirective = ['$animator', function($animator) { return { transclude: 'element', priority: 1000, terminal: true, restrict: 'A', compile: function (element, attr, transclude) { return function ($scope, $element, $attr) { var animate = $animator($scope, $attr); var childElement, childScope; $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { if (childElement) { animate.leave(childElement); childElement = undefined; } if (childScope) { childScope.$destroy(); childScope = undefined; } if (toBoolean(value)) { childScope = $scope.$new(); transclude(childScope, function (clone) { childElement = clone; animate.enter(clone, $element.parent(), $element); }); } }); } } } }]; /** * @ngdoc directive * @name ng.directive:ngInclude * @restrict ECA * * @description * Fetches, compiles and includes an external HTML fragment. * * Keep in mind that Same Origin Policy applies to included resources * (e.g. ngInclude won't work for cross-domain requests on all browsers and for * file:// access on some browsers). * * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter** * and **leave** effects. * * @animations * enter - happens just after the ngInclude contents change and a new DOM element is created and injected into the ngInclude container * leave - happens just after the ngInclude contents change and just before the former contents are removed from the DOM * * @scope * * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the content is loaded. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the expression evaluates to truthy value. * * @example <example animations="true"> <file name="index.html"> <div ng-controller="Ctrl"> <select ng-model="template" ng-options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <tt>{{template.url}}</tt> <hr/> <div class="example-animate-container" ng-include="template.url" ng-animate="{enter: 'example-enter', leave: 'example-leave'}"></div> </div> </file> <file name="script.js"> function Ctrl($scope) { $scope.templates = [ { name: 'template1.html', url: 'template1.html'} , { name: 'template2.html', url: 'template2.html'} ]; $scope.template = $scope.templates[0]; } </file> <file name="template1.html"> <div>Content of template1.html</div> </file> <file name="template2.html"> <div>Content of template2.html</div> </file> <file name="animations.css"> .example-leave, .example-enter { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -ms-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; position:absolute; top:0; left:0; right:0; bottom:0; } .example-animate-container > * { display:block; padding:10px; } .example-enter { top:-50px; } .example-enter.example-enter-active { top:0; } .example-leave { top:0; } .example-leave.example-leave-active { top:50px; } </file> <file name="scenario.js"> it('should load template1.html', function() { expect(element('.doc-example-live [ng-include]').text()). toMatch(/Content of template1.html/); }); it('should load template2.html', function() { select('template').option('1'); expect(element('.doc-example-live [ng-include]').text()). toMatch(/Content of template2.html/); }); it('should change to blank', function() { select('template').option(''); expect(element('.doc-example-live [ng-include]').text()).toEqual(''); }); </file> </example> */ /** * @ngdoc event * @name ng.directive:ngInclude#$includeContentRequested * @eventOf ng.directive:ngInclude * @eventType emit on the scope ngInclude was declared in * @description * Emitted every time the ngInclude content is requested. */ /** * @ngdoc event * @name ng.directive:ngInclude#$includeContentLoaded * @eventOf ng.directive:ngInclude * @eventType emit on the current ngInclude scope * @description * Emitted every time the ngInclude content is reloaded. */ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', '$animator', function($http, $templateCache, $anchorScroll, $compile, $animator) { return { restrict: 'ECA', terminal: true, compile: function(element, attr) { var srcExp = attr.ngInclude || attr.src, onloadExp = attr.onload || '', autoScrollExp = attr.autoscroll; return function(scope, element, attr) { var animate = $animator(scope, attr); var changeCounter = 0, childScope; var clearContent = function() { if (childScope) { childScope.$destroy(); childScope = null; } animate.leave(element.contents(), element); }; scope.$watch(srcExp, function ngIncludeWatchAction(src) { var thisChangeId = ++changeCounter; if (src) { $http.get(src, {cache: $templateCache}).success(function(response) { if (thisChangeId !== changeCounter) return; if (childScope) childScope.$destroy(); childScope = scope.$new(); animate.leave(element.contents(), element); var contents = jqLite('<div/>').html(response).contents(); animate.enter(contents, element); $compile(contents)(childScope); if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } childScope.$emit('$includeContentLoaded'); scope.$eval(onloadExp); }).error(function() { if (thisChangeId === changeCounter) clearContent(); }); scope.$emit('$includeContentRequested'); } else { clearContent(); } }); }; } }; }]; /** * @ngdoc directive * @name ng.directive:ngInit * * @description * The `ngInit` directive specifies initialization tasks to be executed * before the template enters execution mode during bootstrap. * * @element ANY * @param {expression} ngInit {@link guide/expression Expression} to eval. * * @example <doc:example> <doc:source> <div ng-init="greeting='Hello'; person='World'"> {{greeting}} {{person}}! </div> </doc:source> <doc:scenario> it('should check greeting', function() { expect(binding('greeting')).toBe('Hello'); expect(binding('person')).toBe('World'); }); </doc:scenario> </doc:example> */ var ngInitDirective = ngDirective({ compile: function() { return { pre: function(scope, element, attrs) { scope.$eval(attrs.ngInit); } } } }); /** * @ngdoc directive * @name ng.directive:ngNonBindable * @priority 1000 * * @description * Sometimes it is necessary to write code which looks like bindings but which should be left alone * by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML. * * @element ANY * * @example * In this example there are two location where a simple binding (`{{}}`) is present, but the one * wrapped in `ngNonBindable` is left alone. * * @example <doc:example> <doc:source> <div>Normal: {{1 + 2}}</div> <div ng-non-bindable>Ignored: {{1 + 2}}</div> </doc:source> <doc:scenario> it('should check ng-non-bindable', function() { expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); expect(using('.doc-example-live').element('div:last').text()). toMatch(/1 \+ 2/); }); </doc:scenario> </doc:example> */ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); /** * @ngdoc directive * @name ng.directive:ngPluralize * @restrict EA * * @description * # Overview * `ngPluralize` is a directive that displays messages according to en-US localization rules. * These rules are bundled with angular.js and the rules can be overridden * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive * by specifying the mappings between * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} and the strings to be displayed. * * # Plural categories and explicit number rules * There are two * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} in Angular's default en-US locale: "one" and "other". * * While a plural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the * explicit number rule for "3" matches the number 3. You will see the use of plural categories * and explicit number rules throughout later parts of this documentation. * * # Configuring ngPluralize * You configure ngPluralize by providing 2 attributes: `count` and `when`. * You can also provide an optional attribute, `offset`. * * The value of the `count` attribute can be either a string or an {@link guide/expression * Angular expression}; these are evaluated on the current scope for its bound value. * * The `when` attribute specifies the mappings between plural categories and the actual * string to be displayed. The value of the attribute should be a JSON object so that Angular * can interpret it correctly. * * The following example shows how to configure ngPluralize: * * <pre> * <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', * 'one': '1 person is viewing.', * 'other': '{} people are viewing.'}"> * </ng-pluralize> *</pre> * * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for * other numbers, for example 12, so that instead of showing "12 people are viewing", you can * show "a dozen people are viewing". * * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted * into pluralized strings. In the previous example, Angular will replace `{}` with * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder * for <span ng-non-bindable>{{numberExpression}}</span>. * * # Configuring ngPluralize with offset * The `offset` attribute allows further customization of pluralized text, which can result in * a better user experience. For example, instead of the message "4 people are viewing this document", * you might display "John, Kate and 2 others are viewing this document". * The offset attribute allows you to offset a number by any desired value. * Let's take a look at an example: * * <pre> * <ng-pluralize count="personCount" offset=2 * when="{'0': 'Nobody is viewing.', * '1': '{{person1}} is viewing.', * '2': '{{person1}} and {{person2}} are viewing.', * 'one': '{{person1}}, {{person2}} and one other person are viewing.', * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> * </ng-pluralize> * </pre> * * Notice that we are still using two plural categories(one, other), but we added * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" * is shown. * * Note that when you specify offsets, you must provide explicit number rules for * numbers from 0 up to and including the offset. If you use an offset of 3, for example, * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for * plural categories "one" and "other". * * @param {string|expression} count The variable to be bounded to. * @param {string} when The mapping between plural category to its corresponding strings. * @param {number=} offset Offset to deduct from the total number. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.person1 = 'Igor'; $scope.person2 = 'Misko'; $scope.personCount = 1; } </script> <div ng-controller="Ctrl"> Person 1:<input type="text" ng-model="person1" value="Igor" /><br/> Person 2:<input type="text" ng-model="person2" value="Misko" /><br/> Number of People:<input type="text" ng-model="personCount" value="1" /><br/> <!--- Example with simple pluralization rules for en locale ---> Without Offset: <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', 'one': '1 person is viewing.', 'other': '{} people are viewing.'}"> </ng-pluralize><br> <!--- Example with offset ---> With Offset(2): <ng-pluralize count="personCount" offset=2 when="{'0': 'Nobody is viewing.', '1': '{{person1}} is viewing.', '2': '{{person1}} and {{person2}} are viewing.', 'one': '{{person1}}, {{person2}} and one other person are viewing.', 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> </ng-pluralize> </div> </doc:source> <doc:scenario> it('should show correct pluralized string', function() { expect(element('.doc-example-live ng-pluralize:first').text()). toBe('1 person is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor is viewing.'); using('.doc-example-live').input('personCount').enter('0'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('Nobody is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Nobody is viewing.'); using('.doc-example-live').input('personCount').enter('2'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('2 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor and Misko are viewing.'); using('.doc-example-live').input('personCount').enter('3'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('3 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and one other person are viewing.'); using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('4 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); }); it('should show data-binded names', function() { using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); using('.doc-example-live').input('person1').enter('Di'); using('.doc-example-live').input('person2').enter('Vojta'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Di, Vojta and 2 other people are viewing.'); }); </doc:scenario> </doc:example> */ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { var BRACE = /{}/g; return { restrict: 'EA', link: function(scope, element, attr) { var numberExp = attr.count, whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs offset = attr.offset || 0, whens = scope.$eval(whenExp), whensExpFns = {}, startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(); forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + offset + endSymbol)); }); scope.$watch(function ngPluralizeWatch() { var value = parseFloat(scope.$eval(numberExp)); if (!isNaN(value)) { //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, //check it against pluralization rules in $locale service if (!(value in whens)) value = $locale.pluralCat(value - offset); return whensExpFns[value](scope, element, true); } else { return ''; } }, function ngPluralizeWatchAction(newVal) { element.text(newVal); }); } }; }]; /** * @ngdoc directive * @name ng.directive:ngRepeat * * @description * The `ngRepeat` directive instantiates a template once per item from a collection. Each template * instance gets its own scope, where the given loop variable is set to the current collection item, * and `$index` is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) * * `$first` – `{boolean}` – true if the repeated element is first in the iterator. * * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator. * * `$last` – `{boolean}` – true if the repeated element is last in the iterator. * * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter**, * **leave** and **move** effects. * * @animations * enter - when a new item is added to the list or when an item is revealed after a filter * leave - when an item is removed from the list or when an item is filtered out * move - when an adjacent item is filtered out causing a reorder or when the item contents are reordered * * @element ANY * @scope * @priority 1000 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `track in cd.tracks`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function * which can be used to associate the objects in the collection with the DOM elements. If no tractking function * is specified the ng-repeat associates elements by identity in the collection. It is an error to have * more then one tractking function to resolve to the same key. (This would mean that two distinct objects are * mapped to the same DOM element, which is not possible.) * * For example: `item in items` is equivalent to `item in items track by $id(item)'. This implies that the DOM elements * will be associated by item identity in the array. * * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements * with the corresponding item in the array by identity. Moving the same object in array would move the DOM * element in the same way ian the DOM. * * For example: `item in items track by item.id` Is a typical pattern when the items come from the database. In this * case the object identity does not matter. Two objects are considered equivalent as long as their `id` * property is same. * * @example * This example initializes the scope to a list of names and * then uses `ngRepeat` to display every person: <example animations="true"> <file name="index.html"> <div ng-init="friends = [ {name:'John', age:25, gender:'boy'}, {name:'Jessie', age:30, gender:'girl'}, {name:'Johanna', age:28, gender:'girl'}, {name:'Joy', age:15, gender:'girl'}, {name:'Mary', age:28, gender:'girl'}, {name:'Peter', age:95, gender:'boy'}, {name:'Sebastian', age:50, gender:'boy'}, {name:'Erika', age:27, gender:'girl'}, {name:'Patrick', age:40, gender:'boy'}, {name:'Samantha', age:60, gender:'girl'} ]"> I have {{friends.length}} friends. They are: <input type="search" ng-model="q" placeholder="filter friends..." /> <ul> <li ng-repeat="friend in friends | filter:q" ng-animate="{enter: 'example-repeat-enter', leave: 'example-repeat-leave', move: 'example-repeat-move'}"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> </file> <file name="animations.css"> .example-repeat-enter, .example-repeat-leave, .example-repeat-move { -webkit-transition:all linear 0.5s; -moz-transition:all linear 0.5s; -ms-transition:all linear 0.5s; -o-transition:all linear 0.5s; transition:all linear 0.5s; } .example-repeat-enter { line-height:0; opacity:0; } .example-repeat-enter.example-repeat-enter-active { line-height:20px; opacity:1; } .example-repeat-leave { opacity:1; line-height:20px; } .example-repeat-leave.example-repeat-leave-active { opacity:0; line-height:0; } .example-repeat-move { } .example-repeat-move.example-repeat-move-active { } </file> <file name="scenario.js"> it('should render initial data set', function() { var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(10); expect(r.row(0)).toEqual(["1","John","25"]); expect(r.row(1)).toEqual(["2","Jessie","30"]); expect(r.row(9)).toEqual(["10","Samantha","60"]); expect(binding('friends.length')).toBe("10"); }); it('should update repeater when filter predicate changes', function() { var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(10); input('q').enter('ma'); expect(r.count()).toBe(2); expect(r.row(0)).toEqual(["1","Mary","28"]); expect(r.row(1)).toEqual(["2","Samantha","60"]); }); </file> </example> */ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) { var NG_REMOVED = '$$NG_REMOVED'; return { transclude: 'element', priority: 1000, terminal: true, compile: function(element, attr, linker) { return function($scope, $element, $attr){ var animate = $animator($scope, $attr); var expression = $attr.ngRepeat; var match = expression.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/), trackByExp, trackByExpGetter, trackByIdFn, lhs, rhs, valueIdentifier, keyIdentifier, hashFnLocals = {$id: hashKey}; if (!match) { throw Error("Expected ngRepeat in form of '_item_ in _collection_[ track by _id_]' but got '" + expression + "'."); } lhs = match[1]; rhs = match[2]; trackByExp = match[4]; if (trackByExp) { trackByExpGetter = $parse(trackByExp); trackByIdFn = function(key, value, index) { // assign key, value, and $index to the locals so that they can be used in hash functions if (keyIdentifier) hashFnLocals[keyIdentifier] = key; hashFnLocals[valueIdentifier] = value; hashFnLocals.$index = index; return trackByExpGetter($scope, hashFnLocals); }; } else { trackByIdFn = function(key, value) { return hashKey(value); } } match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); if (!match) { throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + lhs + "'."); } valueIdentifier = match[3] || match[1]; keyIdentifier = match[2]; // Store a list of elements from previous run. This is a hash where key is the item from the // iterator, and the value is objects with following properties. // - scope: bound scope // - element: previous element. // - index: position var lastBlockMap = {}; //watch props $scope.$watchCollection(rhs, function ngRepeatAction(collection){ var index, length, cursor = $element, // current position of the node nextCursor, // Same as lastBlockMap but it has the current state. It will become the // lastBlockMap on the next iteration. nextBlockMap = {}, arrayLength, childScope, key, value, // key/value of iteration trackById, collectionKeys, block, // last object information {scope, element, id} nextBlockOrder = []; if (isArrayLike(collection)) { collectionKeys = collection; } else { // if object, extract keys, sort them and use to determine order of iteration over obj props collectionKeys = []; for (key in collection) { if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { collectionKeys.push(key); } } collectionKeys.sort(); } arrayLength = collectionKeys.length; // locate existing items length = nextBlockOrder.length = collectionKeys.length; for(index = 0; index < length; index++) { key = (collection === collectionKeys) ? index : collectionKeys[index]; value = collection[key]; trackById = trackByIdFn(key, value, index); if(lastBlockMap.hasOwnProperty(trackById)) { block = lastBlockMap[trackById] delete lastBlockMap[trackById]; nextBlockMap[trackById] = block; nextBlockOrder[index] = block; } else if (nextBlockMap.hasOwnProperty(trackById)) { // restore lastBlockMap forEach(nextBlockOrder, function(block) { if (block && block.element) lastBlockMap[block.id] = block; }); // This is a duplicate and we need to throw an error throw new Error('Duplicates in a repeater are not allowed. Repeater: ' + expression + ' key: ' + trackById); } else { // new never before seen block nextBlockOrder[index] = { id: trackById }; nextBlockMap[trackById] = false; } } // remove existing items for (key in lastBlockMap) { if (lastBlockMap.hasOwnProperty(key)) { block = lastBlockMap[key]; animate.leave(block.element); block.element[0][NG_REMOVED] = true; block.scope.$destroy(); } } // we are not using forEach for perf reasons (trying to avoid #call) for (index = 0, length = collectionKeys.length; index < length; index++) { key = (collection === collectionKeys) ? index : collectionKeys[index]; value = collection[key]; block = nextBlockOrder[index]; if (block.element) { // if we have already seen this object, then we need to reuse the // associated scope/element childScope = block.scope; nextCursor = cursor[0]; do { nextCursor = nextCursor.nextSibling; } while(nextCursor && nextCursor[NG_REMOVED]); if (block.element[0] == nextCursor) { // do nothing cursor = block.element; } else { // existing item which got moved animate.move(block.element, null, cursor); cursor = block.element; } } else { // new item which we don't know about childScope = $scope.$new(); } childScope[valueIdentifier] = value; if (keyIdentifier) childScope[keyIdentifier] = key; childScope.$index = index; childScope.$first = (index === 0); childScope.$last = (index === (arrayLength - 1)); childScope.$middle = !(childScope.$first || childScope.$last); if (!block.element) { linker(childScope, function(clone) { animate.enter(clone, null, cursor); cursor = clone; block.scope = childScope; block.element = clone; nextBlockMap[block.id] = block; }); } } lastBlockMap = nextBlockMap; }); }; } }; }]; /** * @ngdoc directive * @name ng.directive:ngShow * * @description * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML) * conditionally based on **"truthy"** values evaluated within an {expression}. In other * words, if the expression assigned to **ngShow evaluates to a true value** then **the element is set to visible** * (via `display:block` in css) and **if false** then **the element is set to hidden** (so display:none). * With ngHide this is the reverse whereas true values cause the element itself to become * hidden. * * Additionally, you can also provide animations via the ngAnimate attribute to animate the **show** * and **hide** effects. * * @animations * show - happens after the ngShow expression evaluates to a truthy value and the contents are set to visible * hide - happens before the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden * * @element ANY * @param {expression} ngShow If the {@link guide/expression expression} is truthy * then the element is shown or hidden respectively. * * @example <example animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked"><br/> <div> Show: <span class="check-element" ng-show="checked" ng-animate="{show: 'example-show', hide: 'example-hide'}"> <span class="icon-thumbs-up"></span> I show up when your checkbox is checked. </span> </div> <div> Hide: <span class="check-element" ng-hide="checked" ng-animate="{show: 'example-show', hide: 'example-hide'}"> <span class="icon-thumbs-down"></span> I hide when your checkbox is checked. </span> </div> </file> <file name="animations.css"> .example-show, .example-hide { -webkit-transition:all linear 0.5s; -moz-transition:all linear 0.5s; -ms-transition:all linear 0.5s; -o-transition:all linear 0.5s; transition:all linear 0.5s; } .example-show { line-height:0; opacity:0; padding:0 10px; } .example-show-active.example-show-active { line-height:20px; opacity:1; padding:10px; border:1px solid black; background:white; } .example-hide { line-height:20px; opacity:1; padding:10px; border:1px solid black; background:white; } .example-hide-active.example-hide-active { line-height:0; opacity:0; padding:0 10px; } .check-element { padding:10px; border:1px solid black; background:white; } </file> <file name="scenario.js"> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </file> </example> */ //TODO(misko): refactor to remove element from the DOM var ngShowDirective = ['$animator', function($animator) { return function(scope, element, attr) { var animate = $animator(scope, attr); scope.$watch(attr.ngShow, function ngShowWatchAction(value){ animate[toBoolean(value) ? 'show' : 'hide'](element); }); }; }]; /** * @ngdoc directive * @name ng.directive:ngHide * * @description * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML) * conditionally based on **"truthy"** values evaluated within an {expression}. In other * words, if the expression assigned to **ngShow evaluates to a true value** then **the element is set to visible** * (via `display:block` in css) and **if false** then **the element is set to hidden** (so display:none). * With ngHide this is the reverse whereas true values cause the element itself to become * hidden. * * Additionally, you can also provide animations via the ngAnimate attribute to animate the **show** * and **hide** effects. * * @animations * show - happens after the ngHide expression evaluates to a non truthy value and the contents are set to visible * hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden * * @element ANY * @param {expression} ngHide If the {@link guide/expression expression} is truthy then * the element is shown or hidden respectively. * * @example <example animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked"><br/> <div> Show: <span class="check-element" ng-show="checked" ng-animate="{show: 'example-show', hide: 'example-hide'}"> <span class="icon-thumbs-up"></span> I show up when your checkbox is checked. </span> </div> <div> Hide: <span class="check-element" ng-hide="checked" ng-animate="{show: 'example-show', hide: 'example-hide'}"> <span class="icon-thumbs-down"></span> I hide when your checkbox is checked. </span> </div> </file> <file name="animations.css"> .example-show, .example-hide { -webkit-transition:all linear 0.5s; -moz-transition:all linear 0.5s; -ms-transition:all linear 0.5s; -o-transition:all linear 0.5s; transition:all linear 0.5s; } .example-show { line-height:0; opacity:0; padding:0 10px; } .example-show.example-show-active { line-height:20px; opacity:1; padding:10px; border:1px solid black; background:white; } .example-hide { line-height:20px; opacity:1; padding:10px; border:1px solid black; background:white; } .example-hide.example-hide-active { line-height:0; opacity:0; padding:0 10px; } .check-element { padding:10px; border:1px solid black; background:white; } </file> <file name="scenario.js"> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live .check-element:first:hidden').count()).toEqual(1); expect(element('.doc-example-live .check-element:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live .check-element:first:visible').count()).toEqual(1); expect(element('.doc-example-live .check-element:last:hidden').count()).toEqual(1); }); </file> </example> */ //TODO(misko): refactor to remove element from the DOM var ngHideDirective = ['$animator', function($animator) { return function(scope, element, attr) { var animate = $animator(scope, attr); scope.$watch(attr.ngHide, function ngHideWatchAction(value){ animate[toBoolean(value) ? 'hide' : 'show'](element); }); }; }]; /** * @ngdoc directive * @name ng.directive:ngStyle * * @description * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} ngStyle {@link guide/expression Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * @example <example> <file name="index.html"> <input type="button" value="set" ng-click="myStyle={color:'red'}"> <input type="button" value="clear" ng-click="myStyle={}"> <br/> <span ng-style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </file> <file name="style.css"> span { color: black; } </file> <file name="scenario.js"> it('should check ng-style', function() { expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); element('.doc-example-live :button[value=set]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)'); element('.doc-example-live :button[value=clear]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); }); </file> </example> */ var ngStyleDirective = ngDirective(function(scope, element, attr) { scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { if (oldStyles && (newStyles !== oldStyles)) { forEach(oldStyles, function(val, style) { element.css(style, '');}); } if (newStyles) element.css(newStyles); }, true); }); /** * @ngdoc directive * @name ng.directive:ngSwitch * @restrict EA * * @description * The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression. * Elements within ngSwitch but without ngSwitchWhen or ngSwitchDefault directives will be preserved at the location * as specified in the template. * * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it * from the template cache), ngSwitch simply choses one of the nested elements and makes it visible based on which element * matches the value obtained from the evaluated expression. In other words, you define a container element * (where you place the directive), place an expression on the **on="..." attribute** * (or the **ng-switch="..." attribute**), define any inner elements inside of the directive and place * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default * attribute is displayed. * * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter** * and **leave** effects. * * @animations * enter - happens after the ngSwtich contents change and the matched child element is placed inside the container * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM * * @usage * <ANY ng-switch="expression"> * <ANY ng-switch-when="matchValue1">...</ANY> * <ANY ng-switch-when="matchValue2">...</ANY> * <ANY ng-switch-default>...</ANY> * </ANY> * * @scope * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. * @paramDescription * On child elements add: * * * `ngSwitchWhen`: the case statement to match against. If match then this * case will be displayed. If the same match appears multiple times, all the * elements will be displayed. * * `ngSwitchDefault`: the default case when no other case match. If there * are multiple default cases, all of them will be displayed when no other * case match. * * * @example <example animations="true"> <file name="index.html"> <div ng-controller="Ctrl"> <select ng-model="selection" ng-options="item for item in items"> </select> <tt>selection={{selection}}</tt> <hr/> <div class="example-animate-container" ng-switch on="selection" ng-animate="{enter: 'example-enter', leave: 'example-leave'}"> <div ng-switch-when="settings">Settings Div</div> <div ng-switch-when="home">Home Span</div> <div ng-switch-default>default</div> </div> </div> </file> <file name="script.js"> function Ctrl($scope) { $scope.items = ['settings', 'home', 'other']; $scope.selection = $scope.items[0]; } </file> <file name="animations.css"> .example-leave, .example-enter { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -ms-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; position:absolute; top:0; left:0; right:0; bottom:0; } .example-animate-container > * { display:block; padding:10px; } .example-enter { top:-50px; } .example-enter.example-enter-active { top:0; } .example-leave { top:0; } .example-leave.example-leave-active { top:50px; } </file> <file name="scenario.js"> it('should start in settings', function() { expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); }); it('should change to home', function() { select('selection').option('home'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); }); it('should select default', function() { select('selection').option('other'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); }); </file> </example> */ var ngSwitchDirective = ['$animator', function($animator) { return { restrict: 'EA', require: 'ngSwitch', // asks for $scope to fool the BC controller module controller: ['$scope', function ngSwitchController() { this.cases = {}; }], link: function(scope, element, attr, ngSwitchController) { var animate = $animator(scope, attr); var watchExpr = attr.ngSwitch || attr.on, selectedTranscludes, selectedElements, selectedScopes = []; scope.$watch(watchExpr, function ngSwitchWatchAction(value) { for (var i= 0, ii=selectedScopes.length; i<ii; i++) { selectedScopes[i].$destroy(); animate.leave(selectedElements[i]); } selectedElements = []; selectedScopes = []; if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) { scope.$eval(attr.change); forEach(selectedTranscludes, function(selectedTransclude) { var selectedScope = scope.$new(); selectedScopes.push(selectedScope); selectedTransclude.transclude(selectedScope, function(caseElement) { var anchor = selectedTransclude.element; selectedElements.push(caseElement); animate.enter(caseElement, anchor.parent(), anchor); }); }); } }); } } }]; var ngSwitchWhenDirective = ngDirective({ transclude: 'element', priority: 500, require: '^ngSwitch', compile: function(element, attrs, transclude) { return function(scope, element, attr, ctrl) { ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []); ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: transclude, element: element }); }; } }); var ngSwitchDefaultDirective = ngDirective({ transclude: 'element', priority: 500, require: '^ngSwitch', compile: function(element, attrs, transclude) { return function(scope, element, attr, ctrl) { ctrl.cases['?'] = (ctrl.cases['?'] || []); ctrl.cases['?'].push({ transclude: transclude, element: element }); }; } }); /** * @ngdoc directive * @name ng.directive:ngTransclude * * @description * Insert the transcluded DOM here. * * @element ANY * * @example <doc:example module="transclude"> <doc:source> <script> function Ctrl($scope) { $scope.title = 'Lorem Ipsum'; $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; } angular.module('transclude', []) .directive('pane', function(){ return { restrict: 'E', transclude: true, scope: 'isolate', locals: { title:'bind' }, template: '<div style="border: 1px solid black;">' + '<div style="background-color: gray">{{title}}</div>' + '<div ng-transclude></div>' + '</div>' }; }); </script> <div ng-controller="Ctrl"> <input ng-model="title"><br> <textarea ng-model="text"></textarea> <br/> <pane title="{{title}}">{{text}}</pane> </div> </doc:source> <doc:scenario> it('should have transcluded', function() { input('title').enter('TITLE'); input('text').enter('TEXT'); expect(binding('title')).toEqual('TITLE'); expect(binding('text')).toEqual('TEXT'); }); </doc:scenario> </doc:example> * */ var ngTranscludeDirective = ngDirective({ controller: ['$transclude', '$element', function($transclude, $element) { $transclude(function(clone) { $element.append(clone); }); }] }); /** * @ngdoc directive * @name ng.directive:ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link ng.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter** * and **leave** effects. * * @animations * enter - happens just after the ngView contents are changed (when the new view DOM element is inserted into the DOM) * leave - happens just after the current ngView contents change and just before the former contents are removed from the DOM * * @scope * @example <example module="ngView" animations="true"> <file name="index.html"> <div ng-controller="MainCntl as main"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view class="example-animate-container" ng-animate="{enter: 'example-enter', leave: 'example-leave'}"></div> <hr /> <pre>$location.path() = {{main.$location.path()}}</pre> <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre> <pre>$route.current.params = {{main.$route.current.params}}</pre> <pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre> <pre>$routeParams = {{main.$routeParams}}</pre> </div> </file> <file name="book.html"> <div> controller: {{book.name}}<br /> Book Id: {{book.params.bookId}}<br /> </div> </file> <file name="chapter.html"> <div> controller: {{chapter.name}}<br /> Book Id: {{chapter.params.bookId}}<br /> Chapter Id: {{chapter.params.chapterId}} </div> </file> <file name="animations.css"> .example-leave, .example-enter { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; -ms-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; } .example-animate-container { position:relative; height:100px; } .example-animate-container > * { display:block; width:100%; border-left:1px solid black; position:absolute; top:0; left:0; right:0; bottom:0; padding:10px; } .example-enter { left:100%; } .example-enter.example-enter-active { left:0; } .example-leave { } .example-leave.example-leave-active { left:-100%; } </file> <file name="script.js"> angular.module('ngView', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, controllerAs: 'book' }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl, controllerAs: 'chapter' }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($route, $routeParams, $location) { this.$route = $route; this.$location = $location; this.$routeParams = $routeParams; } function BookCntl($routeParams) { this.name = "BookCntl"; this.params = $routeParams; } function ChapterCntl($routeParams) { this.name = "ChapterCntl"; this.params = $routeParams; } </file> <file name="scenario.js"> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ng.directive:ngView#$viewContentLoaded * @eventOf ng.directive:ngView * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile', '$controller', '$animator', function($http, $templateCache, $route, $anchorScroll, $compile, $controller, $animator) { return { restrict: 'ECA', terminal: true, link: function(scope, element, attr) { var lastScope, onloadExp = attr.onload || '', animate = $animator(scope, attr); scope.$on('$routeChangeSuccess', update); update(); function destroyLastScope() { if (lastScope) { lastScope.$destroy(); lastScope = null; } } function clearContent() { animate.leave(element.contents(), element); destroyLastScope(); } function update() { var locals = $route.current && $route.current.locals, template = locals && locals.$template; if (template) { clearContent(); var enterElements = jqLite('<div></div>').html(template).contents(); animate.enter(enterElements, element); var link = $compile(enterElements), current = $route.current, controller; lastScope = current.scope = scope.$new(); if (current.controller) { locals.$scope = lastScope; controller = $controller(current.controller, locals); if (current.controllerAs) { lastScope[current.controllerAs] = controller; } element.children().data('$ngControllerController', controller); } link(lastScope); lastScope.$emit('$viewContentLoaded'); lastScope.$eval(onloadExp); // $anchorScroll might listen on event... $anchorScroll(); } else { clearContent(); } } } }; }]; /** * @ngdoc directive * @name ng.directive:script * * @description * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the * template can be used by `ngInclude`, `ngView` or directive templates. * * @restrict E * @param {'text/ng-template'} type must be set to `'text/ng-template'` * * @example <doc:example> <doc:source> <script type="text/ng-template" id="/tpl.html"> Content of the template. </script> <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> <div id="tpl-content" ng-include src="currentTpl"></div> </doc:source> <doc:scenario> it('should load template defined inside script tag', function() { element('#tpl-link').click(); expect(element('#tpl-content').text()).toMatch(/Content of the template/); }); </doc:scenario> </doc:example> */ var scriptDirective = ['$templateCache', function($templateCache) { return { restrict: 'E', terminal: true, compile: function(element, attr) { if (attr.type == 'text/ng-template') { var templateUrl = attr.id, // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent text = element[0].text; $templateCache.put(templateUrl, text); } } }; }]; /** * @ngdoc directive * @name ng.directive:select * @restrict E * * @description * HTML `SELECT` element with angular data-binding. * * # `ngOptions` * * Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>` * elements for a `<select>` element using an array or an object obtained by evaluating the * `ngOptions` expression. *˝˝ * When an item in the select menu is select, the value of array element or object property * represented by the selected option will be bound to the model identified by the `ngModel` * directive of the parent select element. * * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can * be nested into the `<select>` element. This element will then represent `null` or "not selected" * option. See example below for demonstration. * * Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead * of {@link ng.directive:ngRepeat ngRepeat} when you want the * `select` model to be bound to a non-string value. This is because an option element can currently * be bound to string values only. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required The control is considered valid only if value is entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {comprehension_expression=} ngOptions in one of the following forms: * * * for array data sources: * * `label` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr` * * for object data sources: * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`group by`** `group` * **`for` `(`**`key`**`,`** `value`**`) in`** `object` * * Where: * * * `array` / `object`: an expression which evaluates to an array / object to iterate over. * * `value`: local variable which will refer to each item in the `array` or each property value * of `object` during iteration. * * `key`: local variable which will refer to a property name in `object` during iteration. * * `label`: The result of this expression will be the label for `<option>` element. The * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). * * `select`: The result of this expression will be bound to the model of the parent `<select>` * element. If not specified, `select` expression will default to `value`. * * `group`: The result of this expression will be used to group options using the `<optgroup>` * DOM element. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be * used to identify the objects in the array. The `trackexpr` will most likely refer to the * `value` variable (e.g. `value.propertyName`). * * @example <doc:example> <doc:source> <script> function MyCntrl($scope) { $scope.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light'}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark'}, {name:'yellow', shade:'light'} ]; $scope.color = $scope.colors[2]; // red } </script> <div ng-controller="MyCntrl"> <ul> <li ng-repeat="color in colors"> Name: <input ng-model="color.name"> [<a href ng-click="colors.splice($index, 1)">X</a>] </li> <li> [<a href ng-click="colors.push({})">add</a>] </li> </ul> <hr/> Color (null not allowed): <select ng-model="color" ng-options="c.name for c in colors"></select><br> Color (null allowed): <span class="nullable"> <select ng-model="color" ng-options="c.name for c in colors"> <option value="">-- chose color --</option> </select> </span><br/> Color grouped by shade: <select ng-model="color" ng-options="c.name group by c.shade for c in colors"> </select><br/> Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br> <hr/> Currently selected: {{ {selected_color:color} }} <div style="border:solid 1px black; height:20px" ng-style="{'background-color':color.name}"> </div> </div> </doc:source> <doc:scenario> it('should check ng-options', function() { expect(binding('{selected_color:color}')).toMatch('red'); select('color').option('0'); expect(binding('{selected_color:color}')).toMatch('black'); using('.nullable').select('color').option(''); expect(binding('{selected_color:color}')).toMatch('null'); }); </doc:scenario> </doc:example> */ var ngOptionsDirective = valueFn({ terminal: true }); var selectDirective = ['$compile', '$parse', function($compile, $parse) { //0000111110000000000022220000000000000000000000333300000000000000444444444444444440000000005555555555555555500000006666666666666666600000000000000007777000000000000000000088888 var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/, nullModelCtrl = {$setViewValue: noop}; return { restrict: 'E', require: ['select', '?ngModel'], controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { var self = this, optionsMap = {}, ngModelCtrl = nullModelCtrl, nullOption, unknownOption; self.databound = $attrs.ngModel; self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { ngModelCtrl = ngModelCtrl_; nullOption = nullOption_; unknownOption = unknownOption_; } self.addOption = function(value) { optionsMap[value] = true; if (ngModelCtrl.$viewValue == value) { $element.val(value); if (unknownOption.parent()) unknownOption.remove(); } }; self.removeOption = function(value) { if (this.hasOption(value)) { delete optionsMap[value]; if (ngModelCtrl.$viewValue == value) { this.renderUnknownOption(value); } } }; self.renderUnknownOption = function(val) { var unknownVal = '? ' + hashKey(val) + ' ?'; unknownOption.val(unknownVal); $element.prepend(unknownOption); $element.val(unknownVal); unknownOption.prop('selected', true); // needed for IE } self.hasOption = function(value) { return optionsMap.hasOwnProperty(value); } $scope.$on('$destroy', function() { // disable unknown option so that we don't do work when the whole select is being destroyed self.renderUnknownOption = noop; }); }], link: function(scope, element, attr, ctrls) { // if ngModel is not defined, we don't need to do anything if (!ctrls[1]) return; var selectCtrl = ctrls[0], ngModelCtrl = ctrls[1], multiple = attr.multiple, optionsExp = attr.ngOptions, nullOption = false, // if false, user will not be able to select it (used by ngOptions) emptyOption, // we can't just jqLite('<option>') since jqLite is not smart enough // to create it in <select> and IE barfs otherwise. optionTemplate = jqLite(document.createElement('option')), optGroupTemplate =jqLite(document.createElement('optgroup')), unknownOption = optionTemplate.clone(); // find "null" option for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) { if (children[i].value == '') { emptyOption = nullOption = children.eq(i); break; } } selectCtrl.init(ngModelCtrl, nullOption, unknownOption); // required validator if (multiple && (attr.required || attr.ngRequired)) { var requiredValidator = function(value) { ngModelCtrl.$setValidity('required', !attr.required || (value && value.length)); return value; }; ngModelCtrl.$parsers.push(requiredValidator); ngModelCtrl.$formatters.unshift(requiredValidator); attr.$observe('required', function() { requiredValidator(ngModelCtrl.$viewValue); }); } if (optionsExp) Options(scope, element, ngModelCtrl); else if (multiple) Multiple(scope, element, ngModelCtrl); else Single(scope, element, ngModelCtrl, selectCtrl); //////////////////////////// function Single(scope, selectElement, ngModelCtrl, selectCtrl) { ngModelCtrl.$render = function() { var viewValue = ngModelCtrl.$viewValue; if (selectCtrl.hasOption(viewValue)) { if (unknownOption.parent()) unknownOption.remove(); selectElement.val(viewValue); if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy } else { if (isUndefined(viewValue) && emptyOption) { selectElement.val(''); } else { selectCtrl.renderUnknownOption(viewValue); } } }; selectElement.bind('change', function() { scope.$apply(function() { if (unknownOption.parent()) unknownOption.remove(); ngModelCtrl.$setViewValue(selectElement.val()); }); }); } function Multiple(scope, selectElement, ctrl) { var lastView; ctrl.$render = function() { var items = new HashMap(ctrl.$viewValue); forEach(selectElement.find('option'), function(option) { option.selected = isDefined(items.get(option.value)); }); }; // we have to do it on each watch since ngModel watches reference, but // we need to work of an array, so we need to see if anything was inserted/removed scope.$watch(function selectMultipleWatch() { if (!equals(lastView, ctrl.$viewValue)) { lastView = copy(ctrl.$viewValue); ctrl.$render(); } }); selectElement.bind('change', function() { scope.$apply(function() { var array = []; forEach(selectElement.find('option'), function(option) { if (option.selected) { array.push(option.value); } }); ctrl.$setViewValue(array); }); }); } function Options(scope, selectElement, ctrl) { var match; if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) { throw Error( "Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_ (track by _expr_)?'" + " but got '" + optionsExp + "'."); } var displayFn = $parse(match[2] || match[1]), valueName = match[4] || match[6], keyName = match[5], groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]), track = match[8], trackFn = track ? $parse(match[8]) : null, // This is an array of array of existing option groups in DOM. We try to reuse these if possible // optionGroupsCache[0] is the options with no option group // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element optionGroupsCache = [[{element: selectElement, label:''}]]; if (nullOption) { // compile the element since there might be bindings in it $compile(nullOption)(scope); // remove the class, which is added automatically because we recompile the element and it // becomes the compilation root nullOption.removeClass('ng-scope'); // we need to remove it before calling selectElement.html('') because otherwise IE will // remove the label from the element. wtf? nullOption.remove(); } // clear contents, we'll add what's needed based on the model selectElement.html(''); selectElement.bind('change', function() { scope.$apply(function() { var optionGroup, collection = valuesFn(scope) || [], locals = {}, key, value, optionElement, index, groupIndex, length, groupLength; if (multiple) { value = []; for (groupIndex = 0, groupLength = optionGroupsCache.length; groupIndex < groupLength; groupIndex++) { // list of options for that group. (first item has the parent) optionGroup = optionGroupsCache[groupIndex]; for(index = 1, length = optionGroup.length; index < length; index++) { if ((optionElement = optionGroup[index].element)[0].selected) { key = optionElement.val(); if (keyName) locals[keyName] = key; if (trackFn) { for (var trackIndex = 0; trackIndex < collection.length; trackIndex++) { locals[valueName] = collection[trackIndex]; if (trackFn(scope, locals) == key) break; } } else { locals[valueName] = collection[key]; } value.push(valueFn(scope, locals)); } } } } else { key = selectElement.val(); if (key == '?') { value = undefined; } else if (key == ''){ value = null; } else { if (trackFn) { for (var trackIndex = 0; trackIndex < collection.length; trackIndex++) { locals[valueName] = collection[trackIndex]; if (trackFn(scope, locals) == key) { value = valueFn(scope, locals); break; } } } else { locals[valueName] = collection[key]; if (keyName) locals[keyName] = key; value = valueFn(scope, locals); } } } ctrl.$setViewValue(value); }); }); ctrl.$render = render; // TODO(vojta): can't we optimize this ? scope.$watch(render); function render() { var optionGroups = {'':[]}, // Temporary location for the option groups before we render them optionGroupNames = [''], optionGroupName, optionGroup, option, existingParent, existingOptions, existingOption, modelValue = ctrl.$modelValue, values = valuesFn(scope) || [], keys = keyName ? sortedKeys(values) : values, groupLength, length, groupIndex, index, locals = {}, selected, selectedSet = false, // nothing is selected yet lastElement, element, label; if (multiple) { if (trackFn && isArray(modelValue)) { selectedSet = new HashMap([]); for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) { locals[valueName] = modelValue[trackIndex]; selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]); } } else { selectedSet = new HashMap(modelValue); } } // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index]; optionGroupName = groupByFn(scope, locals) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } if (multiple) { selected = selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals)) != undefined; } else { if (trackFn) { var modelCast = {}; modelCast[valueName] = modelValue; selected = trackFn(scope, modelCast) === trackFn(scope, locals); } else { selected = modelValue === valueFn(scope, locals); } selectedSet = selectedSet || selected; // see if at least one item is selected } label = displayFn(scope, locals); // what will be seen by the user label = label === undefined ? '' : label; // doing displayFn(scope, locals) || '' overwrites zero values optionGroup.push({ id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index), // either the index into array or key from object label: label, selected: selected // determine if we should be selected }); } if (!multiple) { if (nullOption || modelValue === null) { // insert null option if we have a placeholder, or the model is null optionGroups[''].unshift({id:'', label:'', selected:!selectedSet}); } else if (!selectedSet) { // option could not be found, we have to insert the undefined item optionGroups[''].unshift({id:'?', label:'', selected:true}); } } // Now we need to update the list of DOM nodes to match the optionGroups we computed above for (groupIndex = 0, groupLength = optionGroupNames.length; groupIndex < groupLength; groupIndex++) { // current option group name or '' if no group optionGroupName = optionGroupNames[groupIndex]; // list of options for that group. (first item has the parent) optionGroup = optionGroups[optionGroupName]; if (optionGroupsCache.length <= groupIndex) { // we need to grow the optionGroups existingParent = { element: optGroupTemplate.clone().attr('label', optionGroupName), label: optionGroup.label }; existingOptions = [existingParent]; optionGroupsCache.push(existingOptions); selectElement.append(existingParent.element); } else { existingOptions = optionGroupsCache[groupIndex]; existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element // update the OPTGROUP label if not the same. if (existingParent.label != optionGroupName) { existingParent.element.attr('label', existingParent.label = optionGroupName); } } lastElement = null; // start at the beginning for(index = 0, length = optionGroup.length; index < length; index++) { option = optionGroup[index]; if ((existingOption = existingOptions[index+1])) { // reuse elements lastElement = existingOption.element; if (existingOption.label !== option.label) { lastElement.text(existingOption.label = option.label); } if (existingOption.id !== option.id) { lastElement.val(existingOption.id = option.id); } // lastElement.prop('selected') provided by jQuery has side-effects if (lastElement[0].selected !== option.selected) { lastElement.prop('selected', (existingOption.selected = option.selected)); } } else { // grow elements // if it's a null option if (option.id === '' && nullOption) { // put back the pre-compiled element element = nullOption; } else { // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but // in this version of jQuery on some browser the .text() returns a string // rather then the element. (element = optionTemplate.clone()) .val(option.id) .attr('selected', option.selected) .text(option.label); } existingOptions.push(existingOption = { element: element, label: option.label, id: option.id, selected: option.selected }); if (lastElement) { lastElement.after(element); } else { existingParent.element.append(element); } lastElement = element; } } // remove any excessive OPTIONs in a group index++; // increment since the existingOptions[0] is parent element not OPTION while(existingOptions.length > index) { existingOptions.pop().element.remove(); } } // remove any excessive OPTGROUPs from select while(optionGroupsCache.length > groupIndex) { optionGroupsCache.pop()[0].element.remove(); } } } } } }]; var optionDirective = ['$interpolate', function($interpolate) { var nullSelectCtrl = { addOption: noop, removeOption: noop }; return { restrict: 'E', priority: 100, compile: function(element, attr) { if (isUndefined(attr.value)) { var interpolateFn = $interpolate(element.text(), true); if (!interpolateFn) { attr.$set('value', element.text()); } } return function (scope, element, attr) { var selectCtrlName = '$selectController', parent = element.parent(), selectCtrl = parent.data(selectCtrlName) || parent.parent().data(selectCtrlName); // in case we are in optgroup if (selectCtrl && selectCtrl.databound) { // For some reason Opera defaults to true and if not overridden this messes up the repeater. // We don't want the view to drive the initialization of the model anyway. element.prop('selected', false); } else { selectCtrl = nullSelectCtrl; } if (interpolateFn) { scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) { attr.$set('value', newVal); if (newVal !== oldVal) selectCtrl.removeOption(oldVal); selectCtrl.addOption(newVal); }); } else { selectCtrl.addOption(attr.value); } element.bind('$destroy', function() { selectCtrl.removeOption(attr.value); }); }; } } }]; var styleDirective = valueFn({ restrict: 'E', terminal: true }); /** * Setup file for the Scenario. * Must be first in the compilation/bootstrap list. */ // Public namespace angular.scenario = angular.scenario || {}; /** * Defines a new output format. * * @param {string} name the name of the new output format * @param {function()} fn function(context, runner) that generates the output */ angular.scenario.output = angular.scenario.output || function(name, fn) { angular.scenario.output[name] = fn; }; /** * Defines a new DSL statement. If your factory function returns a Future * it's returned, otherwise the result is assumed to be a map of functions * for chaining. Chained functions are subject to the same rules. * * Note: All functions on the chain are bound to the chain scope so values * set on "this" in your statement function are available in the chained * functions. * * @param {string} name The name of the statement * @param {function()} fn Factory function(), return a function for * the statement. */ angular.scenario.dsl = angular.scenario.dsl || function(name, fn) { angular.scenario.dsl[name] = function() { function executeStatement(statement, args) { var result = statement.apply(this, args); if (angular.isFunction(result) || result instanceof angular.scenario.Future) return result; var self = this; var chain = angular.extend({}, result); angular.forEach(chain, function(value, name) { if (angular.isFunction(value)) { chain[name] = function() { return executeStatement.call(self, value, arguments); }; } else { chain[name] = value; } }); return chain; } var statement = fn.apply(this, arguments); return function() { return executeStatement.call(this, statement, arguments); }; }; }; /** * Defines a new matcher for use with the expects() statement. The value * this.actual (like in Jasmine) is available in your matcher to compare * against. Your function should return a boolean. The future is automatically * created for you. * * @param {string} name The name of the matcher * @param {function()} fn The matching function(expected). */ angular.scenario.matcher = angular.scenario.matcher || function(name, fn) { angular.scenario.matcher[name] = function(expected) { var prefix = 'expect ' + this.future.name + ' '; if (this.inverse) { prefix += 'not '; } var self = this; this.addFuture(prefix + name + ' ' + angular.toJson(expected), function(done) { var error; self.actual = self.future.value; if ((self.inverse && fn.call(self, expected)) || (!self.inverse && !fn.call(self, expected))) { error = 'expected ' + angular.toJson(expected) + ' but was ' + angular.toJson(self.actual); } done(error); }); }; }; /** * Initialize the scenario runner and run ! * * Access global window and document object * Access $runner through closure * * @param {Object=} config Config options */ angular.scenario.setUpAndRun = function(config) { var href = window.location.href; var body = _jQuery(document.body); var output = []; var objModel = new angular.scenario.ObjectModel($runner); if (config && config.scenario_output) { output = config.scenario_output.split(','); } angular.forEach(angular.scenario.output, function(fn, name) { if (!output.length || indexOf(output,name) != -1) { var context = body.append('<div></div>').find('div:last'); context.attr('id', name); fn.call({}, context, $runner, objModel); } }); if (!/^http/.test(href) && !/^https/.test(href)) { body.append('<p id="system-error"></p>'); body.find('#system-error').text( 'Scenario runner must be run using http or https. The protocol ' + href.split(':')[0] + ':// is not supported.' ); return; } var appFrame = body.append('<div id="application"></div>').find('#application'); var application = new angular.scenario.Application(appFrame); $runner.on('RunnerEnd', function() { appFrame.css('display', 'none'); appFrame.find('iframe').attr('src', 'about:blank'); }); $runner.on('RunnerError', function(error) { if (window.console) { console.log(formatException(error)); } else { // Do something for IE alert(error); } }); $runner.run(application); }; /** * Iterates through list with iterator function that must call the * continueFunction to continue iterating. * * @param {Array} list list to iterate over * @param {function()} iterator Callback function(value, continueFunction) * @param {function()} done Callback function(error, result) called when * iteration finishes or an error occurs. */ function asyncForEach(list, iterator, done) { var i = 0; function loop(error, index) { if (index && index > i) { i = index; } if (error || i >= list.length) { done(error); } else { try { iterator(list[i++], loop); } catch (e) { done(e); } } } loop(); } /** * Formats an exception into a string with the stack trace, but limits * to a specific line length. * * @param {Object} error The exception to format, can be anything throwable * @param {Number=} [maxStackLines=5] max lines of the stack trace to include * default is 5. */ function formatException(error, maxStackLines) { maxStackLines = maxStackLines || 5; var message = error.toString(); if (error.stack) { var stack = error.stack.split('\n'); if (stack[0].indexOf(message) === -1) { maxStackLines++; stack.unshift(error.message); } message = stack.slice(0, maxStackLines).join('\n'); } return message; } /** * Returns a function that gets the file name and line number from a * location in the stack if available based on the call site. * * Note: this returns another function because accessing .stack is very * expensive in Chrome. * * @param {Number} offset Number of stack lines to skip */ function callerFile(offset) { var error = new Error(); return function() { var line = (error.stack || '').split('\n')[offset]; // Clean up the stack trace line if (line) { if (line.indexOf('@') !== -1) { // Firefox line = line.substring(line.indexOf('@')+1); } else { // Chrome line = line.substring(line.indexOf('(')+1).replace(')', ''); } } return line || ''; }; } /** * Don't use the jQuery trigger method since it works incorrectly. * * jQuery notifies listeners and then changes the state of a checkbox and * does not create a real browser event. A real click changes the state of * the checkbox and then notifies listeners. * * To work around this we instead use our own handler that fires a real event. */ (function(fn){ var parentTrigger = fn.trigger; fn.trigger = function(type) { if (/(click|change|keydown|blur|input|mousedown|mouseup)/.test(type)) { var processDefaults = []; this.each(function(index, node) { processDefaults.push(browserTrigger(node, type)); }); // this is not compatible with jQuery - we return an array of returned values, // so that scenario runner know whether JS code has preventDefault() of the event or not... return processDefaults; } return parentTrigger.apply(this, arguments); }; })(_jQuery.fn); /** * Finds all bindings with the substring match of name and returns an * array of their values. * * @param {string} bindExp The name to match * @return {Array.<string>} String of binding values */ _jQuery.fn.bindings = function(windowJquery, bindExp) { var result = [], match, bindSelector = '.ng-binding:visible'; if (angular.isString(bindExp)) { bindExp = bindExp.replace(/\s/g, ''); match = function (actualExp) { if (actualExp) { actualExp = actualExp.replace(/\s/g, ''); if (actualExp == bindExp) return true; if (actualExp.indexOf(bindExp) == 0) { return actualExp.charAt(bindExp.length) == '|'; } } } } else if (bindExp) { match = function(actualExp) { return actualExp && bindExp.exec(actualExp); } } else { match = function(actualExp) { return !!actualExp; }; } var selection = this.find(bindSelector); if (this.is(bindSelector)) { selection = selection.add(this); } function push(value) { if (value == undefined) { value = ''; } else if (typeof value != 'string') { value = angular.toJson(value); } result.push('' + value); } selection.each(function() { var element = windowJquery(this), binding; if (binding = element.data('$binding')) { if (typeof binding == 'string') { if (match(binding)) { push(element.scope().$eval(binding)); } } else { if (!angular.isArray(binding)) { binding = [binding]; } for(var fns, j=0, jj=binding.length; j<jj; j++) { fns = binding[j]; if (fns.parts) { fns = fns.parts; } else { fns = [fns]; } for (var scope, fn, i = 0, ii = fns.length; i < ii; i++) { if(match((fn = fns[i]).exp)) { push(fn(scope = scope || element.scope())); } } } } } }); return result; }; (function() { var msie = parseInt((/msie (\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1], 10); function indexOf(array, obj) { if (array.indexOf) return array.indexOf(obj); for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } /** * Triggers a browser event. Attempts to choose the right event if one is * not specified. * * @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement * @param {string} eventType Optional event type. * @param {Array.<string>=} keys Optional list of pressed keys * (valid values: 'alt', 'meta', 'shift', 'ctrl') * @param {number} x Optional x-coordinate for mouse/touch events. * @param {number} y Optional y-coordinate for mouse/touch events. */ window.browserTrigger = function browserTrigger(element, eventType, keys, x, y) { if (element && !element.nodeName) element = element[0]; if (!element) return; var inputType = (element.type) ? element.type.toLowerCase() : null, nodeName = element.nodeName.toLowerCase(); if (!eventType) { eventType = { 'text': 'change', 'textarea': 'change', 'hidden': 'change', 'password': 'change', 'button': 'click', 'submit': 'click', 'reset': 'click', 'image': 'click', 'checkbox': 'click', 'radio': 'click', 'select-one': 'change', 'select-multiple': 'change', '_default_': 'click' }[inputType || '_default_']; } if (nodeName == 'option') { element.parentNode.value = element.value; element = element.parentNode; eventType = 'change'; } keys = keys || []; function pressed(key) { return indexOf(keys, key) !== -1; } if (msie < 9) { if (inputType == 'radio' || inputType == 'checkbox') { element.checked = !element.checked; } // WTF!!! Error: Unspecified error. // Don't know why, but some elements when detached seem to be in inconsistent state and // calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error) // forcing the browser to compute the element position (by reading its CSS) // puts the element in consistent state. element.style.posLeft; // TODO(vojta): create event objects with pressed keys to get it working on IE<9 var ret = element.fireEvent('on' + eventType); if (inputType == 'submit') { while(element) { if (element.nodeName.toLowerCase() == 'form') { element.fireEvent('onsubmit'); break; } element = element.parentNode; } } return ret; } else { var evnt = document.createEvent('MouseEvents'), originalPreventDefault = evnt.preventDefault, appWindow = element.ownerDocument.defaultView, fakeProcessDefault = true, finalProcessDefault, angular = appWindow.angular || {}; // igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208 angular['ff-684208-preventDefault'] = false; evnt.preventDefault = function() { fakeProcessDefault = false; return originalPreventDefault.apply(evnt, arguments); }; x = x || 0; y = y || 0; evnt.initMouseEvent(eventType, true, true, window, 0, x, y, x, y, pressed('ctrl'), pressed('alt'), pressed('shift'), pressed('meta'), 0, element); element.dispatchEvent(evnt); finalProcessDefault = !(angular['ff-684208-preventDefault'] || !fakeProcessDefault); delete angular['ff-684208-preventDefault']; return finalProcessDefault; } } }()); /** * Represents the application currently being tested and abstracts usage * of iframes or separate windows. * * @param {Object} context jQuery wrapper around HTML context. */ angular.scenario.Application = function(context) { this.context = context; context.append( '<h2>Current URL: <a href="about:blank">None</a></h2>' + '<div id="test-frames"></div>' ); }; /** * Gets the jQuery collection of frames. Don't use this directly because * frames may go stale. * * @private * @return {Object} jQuery collection */ angular.scenario.Application.prototype.getFrame_ = function() { return this.context.find('#test-frames iframe:last'); }; /** * Gets the window of the test runner frame. Always favor executeAction() * instead of this method since it prevents you from getting a stale window. * * @private * @return {Object} the window of the frame */ angular.scenario.Application.prototype.getWindow_ = function() { var contentWindow = this.getFrame_().prop('contentWindow'); if (!contentWindow) throw 'Frame window is not accessible.'; return contentWindow; }; /** * Changes the location of the frame. * * @param {string} url The URL. If it begins with a # then only the * hash of the page is changed. * @param {function()} loadFn function($window, $document) Called when frame loads. * @param {function()} errorFn function(error) Called if any error when loading. */ angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) { var self = this; var frame = self.getFrame_(); //TODO(esprehn): Refactor to use rethrow() errorFn = errorFn || function(e) { throw e; }; if (url === 'about:blank') { errorFn('Sandbox Error: Navigating to about:blank is not allowed.'); } else if (url.charAt(0) === '#') { url = frame.attr('src').split('#')[0] + url; frame.attr('src', url); self.executeAction(loadFn); } else { frame.remove(); self.context.find('#test-frames').append('<iframe>'); frame = self.getFrame_(); frame.load(function() { frame.unbind(); try { var $window = self.getWindow_(); if ($window.angular) { // Disable animations // TODO(i): this doesn't disable javascript animations // we don't need that for our tests, but it should be done $window.angular.resumeBootstrap([['$provide', function($provide) { $provide.decorator('$sniffer', function($delegate) { $delegate.transitions = false; $delegate.animations = false; return $delegate; }); }]]); } self.executeAction(loadFn); } catch (e) { errorFn(e); } }).attr('src', url); // for IE compatibility set the name *after* setting the frame url frame[0].contentWindow.name = "NG_DEFER_BOOTSTRAP!"; } self.context.find('> h2 a').attr('href', url).text(url); }; /** * Executes a function in the context of the tested application. Will wait * for all pending angular xhr requests before executing. * * @param {function()} action The callback to execute. function($window, $document) * $document is a jQuery wrapped document. */ angular.scenario.Application.prototype.executeAction = function(action) { var self = this; var $window = this.getWindow_(); if (!$window.document) { throw 'Sandbox Error: Application document not accessible.'; } if (!$window.angular) { return action.call(this, $window, _jQuery($window.document)); } angularInit($window.document, function(element) { var $injector = $window.angular.element(element).injector(); var $element = _jQuery(element); $element.injector = function() { return $injector; }; $injector.invoke(function($browser){ $browser.notifyWhenNoOutstandingRequests(function() { action.call(self, $window, $element); }); }); }); }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; // Shared Unique ID generator for every it (spec) angular.scenario.Describe.specId = 0; /** * Defines a block to execute before each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {function()} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ id: angular.scenario.Describe.specId++, definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.forEach(this.children, function(child) { child.getSpecs(specs); }); angular.forEach(this.its, function(it) { specs.push(it); }); var only = []; angular.forEach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * A future action in a spec. * * @param {string} name of the future action * @param {function()} future callback(error, result) * @param {function()} Optional. function that returns the file/line number. */ angular.scenario.Future = function(name, behavior, line) { this.name = name; this.behavior = behavior; this.fulfilled = false; this.value = undefined; this.parser = angular.identity; this.line = line || function() { return ''; }; }; /** * Executes the behavior of the closure. * * @param {function()} doneFn Callback function(error, result) */ angular.scenario.Future.prototype.execute = function(doneFn) { var self = this; this.behavior(function(error, result) { self.fulfilled = true; if (result) { try { result = self.parser(result); } catch(e) { error = e; } } self.value = error || result; doneFn(error, result); }); }; /** * Configures the future to convert it's final with a function fn(value) * * @param {function()} fn function(value) that returns the parsed value */ angular.scenario.Future.prototype.parsedWith = function(fn) { this.parser = fn; return this; }; /** * Configures the future to parse it's final value from JSON * into objects. */ angular.scenario.Future.prototype.fromJson = function() { return this.parsedWith(angular.fromJson); }; /** * Configures the future to convert it's final value from objects * into JSON. */ angular.scenario.Future.prototype.toJson = function() { return this.parsedWith(angular.toJson); }; /** * Maintains an object tree from the runner events. * * @param {Object} runner The scenario Runner instance to connect to. * * TODO(esprehn): Every output type creates one of these, but we probably * want one global shared instance. Need to handle events better too * so the HTML output doesn't need to do spec model.getSpec(spec.id) * silliness. * * TODO(vojta) refactor on, emit methods (from all objects) - use inheritance */ angular.scenario.ObjectModel = function(runner) { var self = this; this.specMap = {}; this.listeners = []; this.value = { name: '', children: {} }; runner.on('SpecBegin', function(spec) { var block = self.value, definitions = []; angular.forEach(self.getDefinitionPath(spec), function(def) { if (!block.children[def.name]) { block.children[def.name] = { id: def.id, name: def.name, children: {}, specs: {} }; } block = block.children[def.name]; definitions.push(def.name); }); var it = self.specMap[spec.id] = block.specs[spec.name] = new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions); // forward the event self.emit('SpecBegin', it); }); runner.on('SpecError', function(spec, error) { var it = self.getSpec(spec.id); it.status = 'error'; it.error = error; // forward the event self.emit('SpecError', it, error); }); runner.on('SpecEnd', function(spec) { var it = self.getSpec(spec.id); complete(it); // forward the event self.emit('SpecEnd', it); }); runner.on('StepBegin', function(spec, step) { var it = self.getSpec(spec.id); var step = new angular.scenario.ObjectModel.Step(step.name); it.steps.push(step); // forward the event self.emit('StepBegin', it, step); }); runner.on('StepEnd', function(spec) { var it = self.getSpec(spec.id); var step = it.getLastStep(); if (step.name !== step.name) throw 'Events fired in the wrong order. Step names don\'t match.'; complete(step); // forward the event self.emit('StepEnd', it, step); }); runner.on('StepFailure', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('failure', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepFailure', it, modelStep, error); }); runner.on('StepError', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('error', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepError', it, modelStep, error); }); runner.on('RunnerBegin', function() { self.emit('RunnerBegin'); }); runner.on('RunnerEnd', function() { self.emit('RunnerEnd'); }); function complete(item) { item.endTime = new Date().getTime(); item.duration = item.endTime - item.startTime; item.status = item.status || 'success'; } }; /** * Adds a listener for an event. * * @param {string} eventName Name of the event to add a handler for * @param {function()} listener Function that will be called when event is fired */ angular.scenario.ObjectModel.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.ObjectModel.prototype.emit = function(eventName) { var self = this, args = Array.prototype.slice.call(arguments, 1), eventName = eventName.toLowerCase(); if (this.listeners[eventName]) { angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); } }; /** * Computes the path of definition describe blocks that wrap around * this spec. * * @param spec Spec to compute the path for. * @return {Array<Describe>} The describe block path */ angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) { var path = []; var currentDefinition = spec.definition; while (currentDefinition && currentDefinition.name) { path.unshift(currentDefinition); currentDefinition = currentDefinition.parent; } return path; }; /** * Gets a spec by id. * * @param {string} The id of the spec to get the object for. * @return {Object} the Spec instance */ angular.scenario.ObjectModel.prototype.getSpec = function(id) { return this.specMap[id]; }; /** * A single it block. * * @param {string} id Id of the spec * @param {string} name Name of the spec * @param {Array<string>=} definitionNames List of all describe block names that wrap this spec */ angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) { this.id = id; this.name = name; this.startTime = new Date().getTime(); this.steps = []; this.fullDefinitionName = (definitionNames || []).join(' '); }; /** * Adds a new step to the Spec. * * @param {string} step Name of the step (really name of the future) * @return {Object} the added step */ angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) { var step = new angular.scenario.ObjectModel.Step(name); this.steps.push(step); return step; }; /** * Gets the most recent step. * * @return {Object} the step */ angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() { return this.steps[this.steps.length-1]; }; /** * Set status of the Spec from given Step * * @param {angular.scenario.ObjectModel.Step} step */ angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) { if (!this.status || step.status == 'error') { this.status = step.status; this.error = step.error; this.line = step.line; } }; /** * A single step inside a Spec. * * @param {string} step Name of the step */ angular.scenario.ObjectModel.Step = function(name) { this.name = name; this.startTime = new Date().getTime(); }; /** * Helper method for setting all error status related properties * * @param {string} status * @param {string} error * @param {string} line */ angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) { this.status = status; this.error = error; this.line = line; }; /** * Runner for scenarios * * Has to be initialized before any test is loaded, * because it publishes the API into window (global space). */ angular.scenario.Runner = function($window) { this.listeners = []; this.$window = $window; this.rootDescribe = new angular.scenario.Describe(); this.currentDescribe = this.rootDescribe; this.api = { it: this.it, iit: this.iit, xit: angular.noop, describe: this.describe, ddescribe: this.ddescribe, xdescribe: angular.noop, beforeEach: this.beforeEach, afterEach: this.afterEach }; angular.forEach(this.api, angular.bind(this, function(fn, key) { this.$window[key] = angular.bind(this, fn); })); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.Runner.prototype.emit = function(eventName) { var self = this; var args = Array.prototype.slice.call(arguments, 1); eventName = eventName.toLowerCase(); if (!this.listeners[eventName]) return; angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); }; /** * Adds a listener for an event. * * @param {string} eventName The name of the event to add a handler for * @param {string} listener The fn(...) that takes the extra arguments from emit() */ angular.scenario.Runner.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Defines a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.describe = function(name, body) { var self = this; this.currentDescribe.describe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Same as describe, but makes ddescribe the only blocks to run. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.ddescribe = function(name, body) { var self = this; this.currentDescribe.ddescribe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Defines a test in a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.it = function(name, body) { this.currentDescribe.it(name, body); }; /** * Same as it, but makes iit tests the only tests to run. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.iit = function(name, body) { this.currentDescribe.iit(name, body); }; /** * Defines a function to be called before each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {function()} Callback to execute */ angular.scenario.Runner.prototype.beforeEach = function(body) { this.currentDescribe.beforeEach(body); }; /** * Defines a function to be called after each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {function()} Callback to execute */ angular.scenario.Runner.prototype.afterEach = function(body) { this.currentDescribe.afterEach(body); }; /** * Creates a new spec runner. * * @private * @param {Object} scope parent scope */ angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) { var child = scope.$new(); var Cls = angular.scenario.SpecRunner; // Export all the methods to child scope manually as now we don't mess controllers with scopes // TODO(vojta): refactor scenario runner so that these objects are not tightly coupled as current for (var name in Cls.prototype) child[name] = angular.bind(child, Cls.prototype[name]); Cls.call(child); return child; }; /** * Runs all the loaded tests with the specified runner class on the * provided application. * * @param {angular.scenario.Application} application App to remote control. */ angular.scenario.Runner.prototype.run = function(application) { var self = this; var $root = angular.injector(['ng']).get('$rootScope'); angular.extend($root, this); angular.forEach(angular.scenario.Runner.prototype, function(fn, name) { $root[name] = angular.bind(self, fn); }); $root.application = application; $root.emit('RunnerBegin'); asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) { var dslCache = {}; var runner = self.createSpecRunner_($root); angular.forEach(angular.scenario.dsl, function(fn, key) { dslCache[key] = fn.call($root); }); angular.forEach(angular.scenario.dsl, function(fn, key) { self.$window[key] = function() { var line = callerFile(3); var scope = runner.$new(); // Make the dsl accessible on the current chain scope.dsl = {}; angular.forEach(dslCache, function(fn, key) { scope.dsl[key] = function() { return dslCache[key].apply(scope, arguments); }; }); // Make these methods work on the current chain scope.addFuture = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFuture.apply(scope, arguments); }; scope.addFutureAction = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFutureAction.apply(scope, arguments); }; return scope.dsl[key].apply(scope, arguments); }; }); runner.run(spec, function() { runner.$destroy(); specDone.apply(this, arguments); }); }, function(error) { if (error) { self.emit('RunnerError', error); } self.emit('RunnerEnd'); }); }; /** * This class is the "this" of the it/beforeEach/afterEach method. * Responsibilities: * - "this" for it/beforeEach/afterEach * - keep state for single it/beforeEach/afterEach execution * - keep track of all of the futures to execute * - run single spec (execute each future) */ angular.scenario.SpecRunner = function() { this.futures = []; this.afterIndex = 0; }; /** * Executes a spec which is an it block with associated before/after functions * based on the describe nesting. * * @param {Object} spec A spec object * @param {function()} specDone function that is called when the spec finshes. Function(error, index) */ angular.scenario.SpecRunner.prototype.run = function(spec, specDone) { var self = this; this.spec = spec; this.emit('SpecBegin', spec); try { spec.before.call(this); spec.body.call(this); this.afterIndex = this.futures.length; spec.after.call(this); } catch (e) { this.emit('SpecError', spec, e); this.emit('SpecEnd', spec); specDone(); return; } var handleError = function(error, done) { if (self.error) { return done(); } self.error = true; done(null, self.afterIndex); }; asyncForEach( this.futures, function(future, futureDone) { self.step = future; self.emit('StepBegin', spec, future); try { future.execute(function(error) { if (error) { self.emit('StepFailure', spec, future, error); self.emit('StepEnd', spec, future); return handleError(error, futureDone); } self.emit('StepEnd', spec, future); self.$window.setTimeout(function() { futureDone(); }, 0); }); } catch (e) { self.emit('StepError', spec, future, e); self.emit('StepEnd', spec, future); handleError(e, futureDone); } }, function(e) { if (e) { self.emit('SpecError', spec, e); } self.emit('SpecEnd', spec); // Call done in a timeout so exceptions don't recursively // call this function self.$window.setTimeout(function() { specDone(); }, 0); } ); }; /** * Adds a new future action. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {function()} behavior Behavior of the future * @param {function()} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) { var future = new angular.scenario.Future(name, angular.bind(this, behavior), line); this.futures.push(future); return future; }; /** * Adds a new future action to be executed on the application window. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {function()} behavior Behavior of the future * @param {function()} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) { var self = this; var NG = /\[ng\\\:/; return this.addFuture(name, function(done) { this.application.executeAction(function($window, $document) { //TODO(esprehn): Refactor this so it doesn't need to be in here. $document.elements = function(selector) { var args = Array.prototype.slice.call(arguments, 1); selector = (self.selector || '') + ' ' + (selector || ''); selector = _jQuery.trim(selector) || '*'; angular.forEach(args, function(value, index) { selector = selector.replace('$' + (index + 1), value); }); var result = $document.find(selector); if (selector.match(NG)) { angular.forEach(['[ng-','[data-ng-','[x-ng-'], function(value, index){ result = result.add(selector.replace(NG, value), $document); }); } if (!result.length) { throw { type: 'selector', message: 'Selector ' + selector + ' did not match any elements.' }; } return result; }; try { behavior.call(self, $window, $document, done); } catch(e) { if (e.type && e.type === 'selector') { done(e.message); } else { throw e; } } }); }, line); }; /** * Shared DSL statements that are useful to all scenarios. */ /** * Usage: * pause() pauses until you call resume() in the console */ angular.scenario.dsl('pause', function() { return function() { return this.addFuture('pausing for you to resume', function(done) { this.emit('InteractivePause', this.spec, this.step); this.$window.resume = function() { done(); }; }); }; }); /** * Usage: * sleep(seconds) pauses the test for specified number of seconds */ angular.scenario.dsl('sleep', function() { return function(time) { return this.addFuture('sleep for ' + time + ' seconds', function(done) { this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000); }); }; }); /** * Usage: * browser().navigateTo(url) Loads the url into the frame * browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to * browser().reload() refresh the page (reload the same URL) * browser().window.href() window.location.href * browser().window.path() window.location.pathname * browser().window.search() window.location.search * browser().window.hash() window.location.hash without # prefix * browser().location().url() see ng.$location#url * browser().location().path() see ng.$location#path * browser().location().search() see ng.$location#search * browser().location().hash() see ng.$location#hash */ angular.scenario.dsl('browser', function() { var chain = {}; chain.navigateTo = function(url, delegate) { var application = this.application; return this.addFuture("browser navigate to '" + url + "'", function(done) { if (delegate) { url = delegate.call(this, url); } application.navigateTo(url, function() { done(null, url); }, done); }); }; chain.reload = function() { var application = this.application; return this.addFutureAction('browser reload', function($window, $document, done) { var href = $window.location.href; application.navigateTo(href, function() { done(null, href); }, done); }); }; chain.window = function() { var api = {}; api.href = function() { return this.addFutureAction('window.location.href', function($window, $document, done) { done(null, $window.location.href); }); }; api.path = function() { return this.addFutureAction('window.location.path', function($window, $document, done) { done(null, $window.location.pathname); }); }; api.search = function() { return this.addFutureAction('window.location.search', function($window, $document, done) { done(null, $window.location.search); }); }; api.hash = function() { return this.addFutureAction('window.location.hash', function($window, $document, done) { done(null, $window.location.hash.replace('#', '')); }); }; return api; }; chain.location = function() { var api = {}; api.url = function() { return this.addFutureAction('$location.url()', function($window, $document, done) { done(null, $document.injector().get('$location').url()); }); }; api.path = function() { return this.addFutureAction('$location.path()', function($window, $document, done) { done(null, $document.injector().get('$location').path()); }); }; api.search = function() { return this.addFutureAction('$location.search()', function($window, $document, done) { done(null, $document.injector().get('$location').search()); }); }; api.hash = function() { return this.addFutureAction('$location.hash()', function($window, $document, done) { done(null, $document.injector().get('$location').hash()); }); }; return api; }; return function() { return chain; }; }); /** * Usage: * expect(future).{matcher} where matcher is one of the matchers defined * with angular.scenario.matcher * * ex. expect(binding("name")).toEqual("Elliott") */ angular.scenario.dsl('expect', function() { var chain = angular.extend({}, angular.scenario.matcher); chain.not = function() { this.inverse = true; return chain; }; return function(future) { this.future = future; return chain; }; }); /** * Usage: * using(selector, label) scopes the next DSL element selection * * ex. * using('#foo', "'Foo' text field").input('bar') */ angular.scenario.dsl('using', function() { return function(selector, label) { this.selector = _jQuery.trim((this.selector||'') + ' ' + selector); if (angular.isString(label) && label.length) { this.label = label + ' ( ' + this.selector + ' )'; } else { this.label = this.selector; } return this.dsl; }; }); /** * Usage: * binding(name) returns the value of the first matching binding */ angular.scenario.dsl('binding', function() { return function(name) { return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) { var values = $document.elements().bindings($window.angular.element, name); if (!values.length) { return done("Binding selector '" + name + "' did not match."); } done(null, values[0]); }); }; }); /** * Usage: * input(name).enter(value) enters value in input with specified name * input(name).check() checks checkbox * input(name).select(value) selects the radio button with specified name/value * input(name).val() returns the value of the input. */ angular.scenario.dsl('input', function() { var chain = {}; var supportInputEvent = 'oninput' in document.createElement('div') && msie != 9; chain.enter = function(value, event) { return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input'); input.val(value); input.trigger(event || (supportInputEvent ? 'input' : 'change')); done(); }); }; chain.check = function() { return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':checkbox'); input.trigger('click'); done(); }); }; chain.select = function(value) { return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) { var input = $document. elements('[ng\\:model="$1"][value="$2"]', this.name, value).filter(':radio'); input.trigger('click'); done(); }); }; chain.val = function() { return this.addFutureAction("return input val", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input'); done(null,input.val()); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * repeater('#products table', 'Product List').count() number of rows * repeater('#products table', 'Product List').row(1) all bindings in row as an array * repeater('#products table', 'Product List').column('product.name') all values across all rows in an array */ angular.scenario.dsl('repeater', function() { var chain = {}; chain.count = function() { return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.column = function(binding) { return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) { done(null, $document.elements().bindings($window.angular.element, binding)); }); }; chain.row = function(index) { return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) { var matches = $document.elements().slice(index, index + 1); if (!matches.length) return done('row ' + index + ' out of bounds'); done(null, matches.bindings($window.angular.element)); }); }; return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Usage: * select(name).option('value') select one option * select(name).options('value1', 'value2', ...) select options from a multi select */ angular.scenario.dsl('select', function() { var chain = {}; chain.option = function(value) { return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) { var select = $document.elements('select[ng\\:model="$1"]', this.name); var option = select.find('option[value="' + value + '"]'); if (option.length) { select.val(value); } else { option = select.find('option:contains("' + value + '")'); if (option.length) { select.val(option.val()); } else { return done("option '" + value + "' not found"); } } select.trigger('change'); done(); }); }; chain.options = function() { var values = arguments; return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) { var select = $document.elements('select[multiple][ng\\:model="$1"]', this.name); select.val(values); select.trigger('change'); done(); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * element(selector, label).count() get the number of elements that match selector * element(selector, label).click() clicks an element * element(selector, label).mouseover() mouseover an element * element(selector, label).mousedown() mousedown an element * element(selector, label).mouseup() mouseup an element * element(selector, label).query(fn) executes fn(selectedElements, done) * element(selector, label).{method}() gets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr) * element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr) */ angular.scenario.dsl('element', function() { var KEY_VALUE_METHODS = ['attr', 'css', 'prop']; var VALUE_METHODS = [ 'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width', 'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset' ]; var chain = {}; chain.count = function() { return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.click = function() { return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) { var elements = $document.elements(); var href = elements.attr('href'); var eventProcessDefault = elements.trigger('click')[0]; if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) { this.application.navigateTo(href, function() { done(); }, done); } else { done(); } }); }; chain.dblclick = function() { return this.addFutureAction("element '" + this.label + "' dblclick", function($window, $document, done) { var elements = $document.elements(); var href = elements.attr('href'); var eventProcessDefault = elements.trigger('dblclick')[0]; if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) { this.application.navigateTo(href, function() { done(); }, done); } else { done(); } }); }; chain.mouseover = function() { return this.addFutureAction("element '" + this.label + "' mouseover", function($window, $document, done) { var elements = $document.elements(); elements.trigger('mouseover'); done(); }); }; chain.mousedown = function() { return this.addFutureAction("element '" + this.label + "' mousedown", function($window, $document, done) { var elements = $document.elements(); elements.trigger('mousedown'); done(); }); }; chain.mouseup = function() { return this.addFutureAction("element '" + this.label + "' mouseup", function($window, $document, done) { var elements = $document.elements(); elements.trigger('mouseup'); done(); }); }; chain.query = function(fn) { return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) { fn.call(this, $document.elements(), done); }); }; angular.forEach(KEY_VALUE_METHODS, function(methodName) { chain[methodName] = function(name, value) { var args = arguments, futureName = (args.length == 1) ? "element '" + this.label + "' get " + methodName + " '" + name + "'" : "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'"; return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].apply(element, args)); }); }; }); angular.forEach(VALUE_METHODS, function(methodName) { chain[methodName] = function(value) { var args = arguments, futureName = (args.length == 0) ? "element '" + this.label + "' " + methodName : futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'"; return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].apply(element, args)); }); }; }); return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Matchers for implementing specs. Follows the Jasmine spec conventions. */ angular.scenario.matcher('toEqual', function(expected) { return angular.equals(this.actual, expected); }); angular.scenario.matcher('toBe', function(expected) { return this.actual === expected; }); angular.scenario.matcher('toBeDefined', function() { return angular.isDefined(this.actual); }); angular.scenario.matcher('toBeTruthy', function() { return this.actual; }); angular.scenario.matcher('toBeFalsy', function() { return !this.actual; }); angular.scenario.matcher('toMatch', function(expected) { return new RegExp(expected).test(this.actual); }); angular.scenario.matcher('toBeNull', function() { return this.actual === null; }); angular.scenario.matcher('toContain', function(expected) { return includes(this.actual, expected); }); angular.scenario.matcher('toBeLessThan', function(expected) { return this.actual < expected; }); angular.scenario.matcher('toBeGreaterThan', function(expected) { return this.actual > expected; }); /** * User Interface for the Scenario Runner. * * TODO(esprehn): This should be refactored now that ObjectModel exists * to use angular bindings for the UI. */ angular.scenario.output('html', function(context, runner, model) { var specUiMap = {}, lastStepUiMap = {}; context.append( '<div id="header">' + ' <h1><span class="angular">AngularJS</span>: Scenario Test Runner</h1>' + ' <ul id="status-legend" class="status-display">' + ' <li class="status-error">0 Errors</li>' + ' <li class="status-failure">0 Failures</li>' + ' <li class="status-success">0 Passed</li>' + ' </ul>' + '</div>' + '<div id="specs">' + ' <div class="test-children"></div>' + '</div>' ); runner.on('InteractivePause', function(spec) { var ui = lastStepUiMap[spec.id]; ui.find('.test-title'). html('paused... <a href="javascript:resume()">resume</a> when ready.'); }); runner.on('SpecBegin', function(spec) { var ui = findContext(spec); ui.find('> .tests').append( '<li class="status-pending test-it"></li>' ); ui = ui.find('> .tests li:last'); ui.append( '<div class="test-info">' + ' <p class="test-title">' + ' <span class="timer-result"></span>' + ' <span class="test-name"></span>' + ' </p>' + '</div>' + '<div class="scrollpane">' + ' <ol class="test-actions"></ol>' + '</div>' ); ui.find('> .test-info .test-name').text(spec.name); ui.find('> .test-info').click(function() { var scrollpane = ui.find('> .scrollpane'); var actions = scrollpane.find('> .test-actions'); var name = context.find('> .test-info .test-name'); if (actions.find(':visible').length) { actions.hide(); name.removeClass('open').addClass('closed'); } else { actions.show(); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); name.removeClass('closed').addClass('open'); } }); specUiMap[spec.id] = ui; }); runner.on('SpecError', function(spec, error) { var ui = specUiMap[spec.id]; ui.append('<pre></pre>'); ui.find('> pre').text(formatException(error)); }); runner.on('SpecEnd', function(spec) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); ui.removeClass('status-pending'); ui.addClass('status-' + spec.status); ui.find("> .test-info .timer-result").text(spec.duration + "ms"); if (spec.status === 'success') { ui.find('> .test-info .test-name').addClass('closed'); ui.find('> .scrollpane .test-actions').hide(); } updateTotals(spec.status); }); runner.on('StepBegin', function(spec, step) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); ui.find('> .scrollpane .test-actions').append('<li class="status-pending"></li>'); var stepUi = lastStepUiMap[spec.id] = ui.find('> .scrollpane .test-actions li:last'); stepUi.append( '<div class="timer-result"></div>' + '<div class="test-title"></div>' ); stepUi.find('> .test-title').text(step.name); var scrollpane = stepUi.parents('.scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); runner.on('StepFailure', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepError', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepEnd', function(spec, step) { var stepUi = lastStepUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); stepUi.find('.timer-result').text(step.duration + 'ms'); stepUi.removeClass('status-pending'); stepUi.addClass('status-' + step.status); var scrollpane = specUiMap[spec.id].find('> .scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); /** * Finds the context of a spec block defined by the passed definition. * * @param {Object} The definition created by the Describe object. */ function findContext(spec) { var currentContext = context.find('#specs'); angular.forEach(model.getDefinitionPath(spec), function(defn) { var id = 'describe-' + defn.id; if (!context.find('#' + id).length) { currentContext.find('> .test-children').append( '<div class="test-describe" id="' + id + '">' + ' <h2></h2>' + ' <div class="test-children"></div>' + ' <ul class="tests"></ul>' + '</div>' ); context.find('#' + id).find('> h2').text('describe: ' + defn.name); } currentContext = context.find('#' + id); }); return context.find('#describe-' + spec.definition.id); } /** * Updates the test counter for the status. * * @param {string} the status. */ function updateTotals(status) { var legend = context.find('#status-legend .status-' + status); var parts = legend.text().split(' '); var value = (parts[0] * 1) + 1; legend.text(value + ' ' + parts[1]); } /** * Add an error to a step. * * @param {Object} The JQuery wrapped context * @param {function()} fn() that should return the file/line number of the error * @param {Object} the error. */ function addError(context, line, error) { context.find('.test-title').append('<pre></pre>'); var message = _jQuery.trim(line() + '\n\n' + formatException(error)); context.find('.test-title pre:last').text(message); } }); /** * Generates JSON output into a context. */ angular.scenario.output('json', function(context, runner, model) { model.on('RunnerEnd', function() { context.text(angular.toJson(model.value)); }); }); /** * Generates XML output into a context. */ angular.scenario.output('xml', function(context, runner, model) { var $ = function(args) {return new context.init(args);}; model.on('RunnerEnd', function() { var scenario = $('<scenario></scenario>'); context.append(scenario); serializeXml(scenario, model.value); }); /** * Convert the tree into XML. * * @param {Object} context jQuery context to add the XML to. * @param {Object} tree node to serialize */ function serializeXml(context, tree) { angular.forEach(tree.children, function(child) { var describeContext = $('<describe></describe>'); describeContext.attr('id', child.id); describeContext.attr('name', child.name); context.append(describeContext); serializeXml(describeContext, child); }); var its = $('<its></its>'); context.append(its); angular.forEach(tree.specs, function(spec) { var it = $('<it></it>'); it.attr('id', spec.id); it.attr('name', spec.name); it.attr('duration', spec.duration); it.attr('status', spec.status); its.append(it); angular.forEach(spec.steps, function(step) { var stepContext = $('<step></step>'); stepContext.attr('name', step.name); stepContext.attr('duration', step.duration); stepContext.attr('status', step.status); it.append(stepContext); if (step.error) { var error = $('<error></error>'); stepContext.append(error); error.text(formatException(step.error)); } }); }); } }); /** * Creates a global value $result with the result of the runner. */ angular.scenario.output('object', function(context, runner, model) { runner.$window.$result = model.value; }); bindJQuery(); publishExternalAPI(angular); var $runner = new angular.scenario.Runner(window), scripts = document.getElementsByTagName('script'), script = scripts[scripts.length - 1], config = {}; angular.forEach(script.attributes, function(attr) { var match = attr.name.match(/ng[:\-](.*)/); if (match) { config[match[1]] = attr.value || true; } }); if (config.autotest) { JQLite(document).ready(function() { angular.scenario.setUpAndRun(config); }); } })(window, document); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n\n[ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],\n.ng-cloak, .x-ng-cloak {\n display: none;\n}\n\nng\\:form {\n display: block;\n}\n</style>'); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>');
test/server/ModalSpec.js
chilts/react-bootstrap
import React from 'react'; import {assert} from 'chai'; import Modal from '../../src/Modal.js'; describe('Modal', () => { it('Should be rendered on the server side', function () { let noOp = () => {}; assert.doesNotThrow(function renderOnServerSide() { return React.renderToString( <Modal onHide={noOp}> <strong>Message</strong> </Modal> ); }); }); });
react/features/polls/components/native/PollItem.js
jitsi/jitsi-meet
// @flow import React from 'react'; import { View } from 'react-native'; import { useSelector } from 'react-redux'; import { shouldShowResults } from '../../functions'; import PollAnswer from './PollAnswer'; import PollResults from './PollResults'; import { chatStyles } from './styles'; type Props = { /** * Id of the poll. */ pollId: string, } const PollItem = ({ pollId }: Props) => { const showResults = useSelector(shouldShowResults(pollId)); return ( <View style = { chatStyles.pollItemContainer }> { showResults ? <PollResults key = { pollId } pollId = { pollId } /> : <PollAnswer pollId = { pollId } /> } </View> ); }; export default PollItem;
files/videojs/5.0.0-rc.33/video.js
PeterDaveHello/jsdelivr
/** * @license * Video.js 5.0.0-rc.33 <http://videojs.com/> * Copyright Brightcove, Inc. <https://www.brightcove.com/> * Available under Apache License Version 2.0 * <https://github.com/videojs/video.js/blob/master/LICENSE> * * Includes vtt.js <https://github.com/mozilla/vtt.js> * Available under Apache License Version 2.0 * <https://github.com/mozilla/vtt.js/blob/master/LICENSE> */ (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.videojs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ (function (global){ var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = _dereq_('min-document'); if (typeof document !== 'undefined') { module.exports = document; } else { var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } module.exports = doccy; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"min-document":3}],2:[function(_dereq_,module,exports){ (function (global){ if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],3:[function(_dereq_,module,exports){ },{}],4:[function(_dereq_,module,exports){ /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as an array. * * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters). * * @static * @memberOf _ * @category Function * @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. * @example * * var say = _.restParam(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function restParam(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length); while (++index < length) { rest[index] = args[start + index]; } switch (start) { case 0: return func.call(this, rest); case 1: return func.call(this, args[0], rest); case 2: return func.call(this, args[0], args[1], rest); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = rest; return func.apply(this, otherArgs); }; } module.exports = restParam; },{}],5:[function(_dereq_,module,exports){ /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = arrayCopy; },{}],6:[function(_dereq_,module,exports){ /** * A specialized version of `_.forEach` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; },{}],7:[function(_dereq_,module,exports){ /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property names to copy. * @param {Object} [object={}] The object to copy properties to. * @returns {Object} Returns `object`. */ function baseCopy(source, props, object) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; object[key] = source[key]; } return object; } module.exports = baseCopy; },{}],8:[function(_dereq_,module,exports){ var createBaseFor = _dereq_('./createBaseFor'); /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `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; },{"./createBaseFor":17}],9:[function(_dereq_,module,exports){ var baseFor = _dereq_('./baseFor'), keysIn = _dereq_('../object/keysIn'); /** * The base implementation of `_.forIn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForIn(object, iteratee) { return baseFor(object, iteratee, keysIn); } module.exports = baseForIn; },{"../object/keysIn":39,"./baseFor":8}],10:[function(_dereq_,module,exports){ /** * The base implementation of `_.isFunction` without support for environments * with incorrect `typeof` results. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. */ function baseIsFunction(value) { // Avoid a Chakra JIT bug in compatibility modes of IE 11. // See https://github.com/jashkenas/underscore/issues/1621 for more details. return typeof value == 'function' || false; } module.exports = baseIsFunction; },{}],11:[function(_dereq_,module,exports){ var arrayEach = _dereq_('./arrayEach'), baseMergeDeep = _dereq_('./baseMergeDeep'), isArray = _dereq_('../lang/isArray'), isArrayLike = _dereq_('./isArrayLike'), isObject = _dereq_('../lang/isObject'), isObjectLike = _dereq_('./isObjectLike'), isTypedArray = _dereq_('../lang/isTypedArray'), keys = _dereq_('../object/keys'); /** * The base implementation of `_.merge` without support for argument juggling, * multiple sources, and `this` binding `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} [customizer] The function to customize merging properties. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {Object} Returns `object`. */ function baseMerge(object, source, customizer, stackA, stackB) { if (!isObject(object)) { return object; } var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)), props = isSrcArr ? null : keys(source); arrayEach(props || source, function(srcValue, key) { if (props) { key = srcValue; srcValue = source[key]; } if (isObjectLike(srcValue)) { stackA || (stackA = []); stackB || (stackB = []); baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); } else { var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; } if ((result !== undefined || (isSrcArr && !(key in object))) && (isCommon || (result === result ? (result !== value) : (value === value)))) { object[key] = result; } } }); return object; } module.exports = baseMerge; },{"../lang/isArray":30,"../lang/isObject":33,"../lang/isTypedArray":36,"../object/keys":38,"./arrayEach":6,"./baseMergeDeep":12,"./isArrayLike":20,"./isObjectLike":25}],12:[function(_dereq_,module,exports){ var arrayCopy = _dereq_('./arrayCopy'), isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isArrayLike = _dereq_('./isArrayLike'), isPlainObject = _dereq_('../lang/isPlainObject'), isTypedArray = _dereq_('../lang/isTypedArray'), toPlainObject = _dereq_('../lang/toPlainObject'); /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize merging properties. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { var length = stackA.length, srcValue = source[key]; while (length--) { if (stackA[length] == srcValue) { object[key] = stackB[length]; return; } } var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) { result = isArray(value) ? value : (isArrayLike(value) ? arrayCopy(value) : []); } else if (isPlainObject(srcValue) || isArguments(srcValue)) { result = isArguments(value) ? toPlainObject(value) : (isPlainObject(value) ? value : {}); } else { isCommon = false; } } // Add the source value to the stack of traversed objects and associate // it with its merged value. stackA.push(srcValue); stackB.push(result); if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); } else if (result === result ? (result !== value) : (value === value)) { object[key] = result; } } module.exports = baseMergeDeep; },{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isPlainObject":34,"../lang/isTypedArray":36,"../lang/toPlainObject":37,"./arrayCopy":5,"./isArrayLike":20}],13:[function(_dereq_,module,exports){ var toObject = _dereq_('./toObject'); /** * 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 function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : toObject(object)[key]; }; } module.exports = baseProperty; },{"./toObject":28}],14:[function(_dereq_,module,exports){ /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } module.exports = baseToString; },{}],15:[function(_dereq_,module,exports){ var identity = _dereq_('../utility/identity'); /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } module.exports = bindCallback; },{"../utility/identity":43}],16:[function(_dereq_,module,exports){ var bindCallback = _dereq_('./bindCallback'), isIterateeCall = _dereq_('./isIterateeCall'), restParam = _dereq_('../function/restParam'); /** * Creates a function that assigns properties of source object(s) to a given * destination object. * * **Note:** This function is used to create `_.assign`, `_.defaults`, and `_.merge`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return restParam(function(object, sources) { var index = -1, length = object == null ? 0 : sources.length, customizer = length > 2 ? sources[length - 2] : undefined, guard = length > 2 ? sources[2] : undefined, thisArg = length > 1 ? sources[length - 1] : undefined; if (typeof customizer == 'function') { customizer = bindCallback(customizer, thisArg, 5); length -= 2; } else { customizer = typeof thisArg == 'function' ? thisArg : undefined; length -= (customizer ? 1 : 0); } if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; }); } module.exports = createAssigner; },{"../function/restParam":4,"./bindCallback":15,"./isIterateeCall":23}],17:[function(_dereq_,module,exports){ var toObject = _dereq_('./toObject'); /** * Creates a base function for `_.forIn` or `_.forInRight`. * * @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 iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; },{"./toObject":28}],18:[function(_dereq_,module,exports){ var baseProperty = _dereq_('./baseProperty'); /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); module.exports = getLength; },{"./baseProperty":13}],19:[function(_dereq_,module,exports){ var isNative = _dereq_('../lang/isNative'); /** * 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 = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } module.exports = getNative; },{"../lang/isNative":32}],20:[function(_dereq_,module,exports){ var getLength = _dereq_('./getLength'), isLength = _dereq_('./isLength'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } module.exports = isArrayLike; },{"./getLength":18,"./isLength":24}],21:[function(_dereq_,module,exports){ /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ var isHostObject = (function() { try { Object({ 'toString': 0 } + ''); } catch(e) { return function() { return false; }; } return function(value) { // IE < 9 presents many host objects as `Object` objects that can coerce // to strings despite having improperly defined `toString` methods. return typeof value.toString != 'function' && typeof (value + '') == 'string'; }; }()); module.exports = isHostObject; },{}],22:[function(_dereq_,module,exports){ /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } module.exports = isIndex; },{}],23:[function(_dereq_,module,exports){ var isArrayLike = _dereq_('./isArrayLike'), isIndex = _dereq_('./isIndex'), isObject = _dereq_('../lang/isObject'); /** * Checks if the provided 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)) { var other = object[index]; return value === value ? (value === other) : (other !== other); } return false; } module.exports = isIterateeCall; },{"../lang/isObject":33,"./isArrayLike":20,"./isIndex":22}],24:[function(_dereq_,module,exports){ /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; },{}],25:[function(_dereq_,module,exports){ /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; },{}],26:[function(_dereq_,module,exports){ var baseForIn = _dereq_('./baseForIn'), isArguments = _dereq_('../lang/isArguments'), isHostObject = _dereq_('./isHostObject'), isObjectLike = _dereq_('./isObjectLike'), support = _dereq_('../support'); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * A fallback implementation of `_.isPlainObject` which checks if `value` * is an object created by the `Object` constructor or has a `[[Prototype]]` * of `null`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. */ function shimIsPlainObject(value) { var Ctor; // Exit early for non `Object` objects. if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isHostObject(value)) || (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor))) || (!support.argsTag && isArguments(value))) { return false; } // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. var result; if (support.ownLast) { baseForIn(value, function(subValue, key, object) { result = hasOwnProperty.call(object, key); return false; }); return result !== false; } // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. baseForIn(value, function(subValue, key) { result = key; }); return result === undefined || hasOwnProperty.call(value, result); } module.exports = shimIsPlainObject; },{"../lang/isArguments":29,"../support":42,"./baseForIn":9,"./isHostObject":21,"./isObjectLike":25}],27:[function(_dereq_,module,exports){ var isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isIndex = _dereq_('./isIndex'), isLength = _dereq_('./isLength'), isString = _dereq_('../lang/isString'), keysIn = _dereq_('../object/keysIn'); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A fallback implementation of `Object.keys` which creates an array of the * own enumerable property names of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length; var allowIndexes = !!length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } module.exports = shimKeys; },{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isString":35,"../object/keysIn":39,"./isIndex":22,"./isLength":24}],28:[function(_dereq_,module,exports){ var isObject = _dereq_('../lang/isObject'), isString = _dereq_('../lang/isString'), support = _dereq_('../support'); /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { if (support.unindexedChars && isString(value)) { var index = -1, length = value.length, result = Object(value); while (++index < length) { result[index] = value.charAt(index); } return result; } return isObject(value) ? value : Object(value); } module.exports = toObject; },{"../lang/isObject":33,"../lang/isString":35,"../support":42}],29:[function(_dereq_,module,exports){ var isArrayLike = _dereq_('../internal/isArrayLike'), isObjectLike = _dereq_('../internal/isObjectLike'), support = _dereq_('../support'); /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is classified as an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return isObjectLike(value) && isArrayLike(value) && objToString.call(value) == argsTag; } // Fallback for environments without a `toStringTag` for `arguments` objects. if (!support.argsTag) { isArguments = function(value) { return isObjectLike(value) && isArrayLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; } module.exports = isArguments; },{"../internal/isArrayLike":20,"../internal/isObjectLike":25,"../support":42}],30:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isLength = _dereq_('../internal/isLength'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var arrayTag = '[object Array]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; module.exports = isArray; },{"../internal/getNative":19,"../internal/isLength":24,"../internal/isObjectLike":25}],31:[function(_dereq_,module,exports){ (function (global){ var baseIsFunction = _dereq_('../internal/baseIsFunction'), getNative = _dereq_('../internal/getNative'); /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Native method references. */ var Uint8Array = getNative(global, 'Uint8Array'); /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ var isFunction = !(baseIsFunction(/x/) || (Uint8Array && !baseIsFunction(Uint8Array))) ? baseIsFunction : function(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 equivalents which return 'object' for typed array constructors. return objToString.call(value) == funcTag; }; module.exports = isFunction; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../internal/baseIsFunction":10,"../internal/getNative":19}],32:[function(_dereq_,module,exports){ var escapeRegExp = _dereq_('../string/escapeRegExp'), isHostObject = _dereq_('../internal/isHostObject'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + escapeRegExp(fnToString.call(hasOwnProperty)) .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (objToString.call(value) == funcTag) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value); } module.exports = isNative; },{"../internal/isHostObject":21,"../internal/isObjectLike":25,"../string/escapeRegExp":41}],33:[function(_dereq_,module,exports){ /** * 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; },{}],34:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isArguments = _dereq_('./isArguments'), shimIsPlainObject = _dereq_('../internal/shimIsPlainObject'), support = _dereq_('../support'); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Native method references. */ var getPrototypeOf = getNative(Object, 'getPrototypeOf'); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * **Note:** This method assumes objects created by the `Object` constructor * have no inherited enumerable properties. * * @static * @memberOf _ * @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 */ var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { if (!(value && objToString.call(value) == objectTag) || (!support.argsTag && isArguments(value))) { return false; } var valueOf = getNative(value, 'valueOf'), objProto = valueOf && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); return objProto ? (value == objProto || getPrototypeOf(value) == objProto) : shimIsPlainObject(value); }; module.exports = isPlainObject; },{"../internal/getNative":19,"../internal/shimIsPlainObject":26,"../support":42,"./isArguments":29}],35:[function(_dereq_,module,exports){ var isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); } module.exports = isString; },{"../internal/isObjectLike":25}],36:[function(_dereq_,module,exports){ var isLength = _dereq_('../internal/isLength'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `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]', 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[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; } module.exports = isTypedArray; },{"../internal/isLength":24,"../internal/isObjectLike":25}],37:[function(_dereq_,module,exports){ var baseCopy = _dereq_('../internal/baseCopy'), keysIn = _dereq_('../object/keysIn'); /** * Converts `value` to a plain object flattening inherited enumerable * properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return baseCopy(value, keysIn(value)); } module.exports = toPlainObject; },{"../internal/baseCopy":7,"../object/keysIn":39}],38:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isArrayLike = _dereq_('../internal/isArrayLike'), isObject = _dereq_('../lang/isObject'), shimKeys = _dereq_('../internal/shimKeys'), support = _dereq_('../support'); /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys) * for more details. * * @static * @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'] */ var keys = !nativeKeys ? shimKeys : function(object) { var Ctor = object == null ? null : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object == 'function' ? support.enumPrototypes : isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; module.exports = keys; },{"../internal/getNative":19,"../internal/isArrayLike":20,"../internal/shimKeys":27,"../lang/isObject":33,"../support":42}],39:[function(_dereq_,module,exports){ var arrayEach = _dereq_('../internal/arrayEach'), isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isFunction = _dereq_('../lang/isFunction'), isIndex = _dereq_('../internal/isIndex'), isLength = _dereq_('../internal/isLength'), isObject = _dereq_('../lang/isObject'), isString = _dereq_('../lang/isString'), support = _dereq_('../support'); /** `Object#toString` result references. */ var arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', stringTag = '[object String]'; /** Used to fix the JScript `[[DontEnum]]` bug. */ var shadowProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** Used for native method references. */ var errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to avoid iterating over non-enumerable properties in IE < 9. */ var nonEnumProps = {}; nonEnumProps[arrayTag] = nonEnumProps[dateTag] = nonEnumProps[numberTag] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolTag] = nonEnumProps[stringTag] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorTag] = nonEnumProps[funcTag] = nonEnumProps[regexpTag] = { 'constructor': true, 'toString': true }; nonEnumProps[objectTag] = { 'constructor': true }; arrayEach(shadowProps, function(key) { for (var tag in nonEnumProps) { if (hasOwnProperty.call(nonEnumProps, tag)) { var props = nonEnumProps[tag]; props[key] = hasOwnProperty.call(props, key); } } }); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @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; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)) && length) || 0; var Ctor = object.constructor, index = -1, proto = (isFunction(Ctor) && Ctor.prototype) || objectProto, isProto = proto === object, result = Array(length), skipIndexes = length > 0, skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error), skipProto = support.enumPrototypes && isFunction(object); while (++index < length) { result[index] = (index + ''); } // lodash skips the `constructor` property when it infers it is iterating // over a `prototype` object because IE < 9 can't set the `[[Enumerable]]` // attribute of an existing property and the `constructor` property of a // prototype defaults to non-enumerable. for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name')) && !(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var tag = object === stringProto ? stringTag : (object === errorProto ? errorTag : objToString.call(object)), nonEnums = nonEnumProps[tag] || nonEnumProps[objectTag]; if (tag == objectTag) { proto = objectProto; } length = shadowProps.length; while (length--) { key = shadowProps[length]; var nonEnum = nonEnums[key]; if (!(isProto && nonEnum) && (nonEnum ? hasOwnProperty.call(object, key) : object[key] !== proto[key])) { result.push(key); } } } return result; } module.exports = keysIn; },{"../internal/arrayEach":6,"../internal/isIndex":22,"../internal/isLength":24,"../lang/isArguments":29,"../lang/isArray":30,"../lang/isFunction":31,"../lang/isObject":33,"../lang/isString":35,"../support":42}],40:[function(_dereq_,module,exports){ var baseMerge = _dereq_('../internal/baseMerge'), createAssigner = _dereq_('../internal/createAssigner'); /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined` into the destination object. Subsequent sources * overwrite property assignments of previous sources. If `customizer` is * provided it is invoked to produce the merged values of the destination and * source properties. If `customizer` returns `undefined` merging is handled * by the method instead. The `customizer` is bound to `thisArg` and invoked * with five arguments: (objectValue, sourceValue, key, object, source). * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example * * var users = { * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] * }; * * var ages = { * 'data': [{ 'age': 36 }, { 'age': 40 }] * }; * * _.merge(users, ages); * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } * * // using a customizer callback * var object = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var other = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(object, other, function(a, b) { * if (_.isArray(a)) { * return a.concat(b); * } * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } */ var merge = createAssigner(baseMerge); module.exports = merge; },{"../internal/baseMerge":11,"../internal/createAssigner":16}],41:[function(_dereq_,module,exports){ var baseToString = _dereq_('../internal/baseToString'); /** * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). * In addition to special characters the forward slash is escaped to allow for * easier `eval` use and `Function` compilation. */ var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); /** * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' */ function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } module.exports = escapeRegExp; },{"../internal/baseToString":14}],42:[function(_dereq_,module,exports){ (function (global){ /** `Object#toString` result references. */ var argsTag = '[object Arguments]', objectTag = '[object Object]'; /** Used for native method references. */ var arrayProto = Array.prototype, errorProto = Error.prototype, objectProto = Object.prototype; /** Used to detect DOM support. */ var document = (document = global.window) ? document.document : null; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice; /** * An object environment feature flags. * * @static * @memberOf _ * @type Object */ var support = {}; (function(x) { var Ctor = function() { this.x = x; }, object = { '0': x, 'length': x }, props = []; Ctor.prototype = { 'valueOf': x, 'y': x }; for (var key in new Ctor) { props.push(key); } /** * Detect if the `toStringTag` of `arguments` objects is resolvable * (all but Firefox < 4, IE < 9). * * @memberOf _.support * @type boolean */ support.argsTag = objToString.call(arguments) == argsTag; /** * Detect if `name` or `message` properties of `Error.prototype` are * enumerable by default (IE < 9, Safari < 5.1). * * @memberOf _.support * @type boolean */ support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); /** * Detect if `prototype` properties are enumerable by default. * * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 * (if the prototype or a property on the prototype has been set) * incorrectly set the `[[Enumerable]]` value of a function's `prototype` * property to `true`. * * @memberOf _.support * @type boolean */ support.enumPrototypes = propertyIsEnumerable.call(Ctor, 'prototype'); /** * Detect if the `toStringTag` of DOM nodes is resolvable (all but IE < 9). * * @memberOf _.support * @type boolean */ support.nodeTag = objToString.call(document) != objectTag; /** * Detect if properties shadowing those on `Object.prototype` are non-enumerable. * * In IE < 9 an object's own properties, shadowing non-enumerable ones, * are made non-enumerable as well (a.k.a the JScript `[[DontEnum]]` bug). * * @memberOf _.support * @type boolean */ support.nonEnumShadows = !/valueOf/.test(props); /** * Detect if own properties are iterated after inherited properties (IE < 9). * * @memberOf _.support * @type boolean */ support.ownLast = props[0] != 'x'; /** * Detect if `Array#shift` and `Array#splice` augment array-like objects * correctly. * * Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array * `shift()` and `splice()` functions that fail to remove the last element, * `value[0]`, of array-like objects even though the "length" property is * set to `0`. The `shift()` method is buggy in compatibility modes of IE 8, * while `splice()` is buggy regardless of mode in IE < 9. * * @memberOf _.support * @type boolean */ support.spliceObjects = (splice.call(object, 0, 1), !object[0]); /** * Detect lack of support for accessing string characters by index. * * IE < 8 can't access characters by index. IE 8 can only access characters * by index on string literals, not string objects. * * @memberOf _.support * @type boolean */ support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; /** * Detect if the DOM is supported. * * @memberOf _.support * @type boolean */ try { support.dom = document.createDocumentFragment().nodeType === 11; } catch(e) { support.dom = false; } }(1, 0)); module.exports = support; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],43:[function(_dereq_,module,exports){ /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = identity; },{}],44:[function(_dereq_,module,exports){ 'use strict'; // modified from https://github.com/es-shims/es6-shim var keys = _dereq_('object-keys'); var canBeObject = function (obj) { return typeof obj !== 'undefined' && obj !== null; }; var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; var defineProperties = _dereq_('define-properties'); var propIsEnumerable = Object.prototype.propertyIsEnumerable; var isEnumerableOn = function (obj) { return function isEnumerable(prop) { return propIsEnumerable.call(obj, prop); }; }; var assignShim = function assign(target, source1) { if (!canBeObject(target)) { throw new TypeError('target must be an object'); } var objTarget = Object(target); var s, source, i, props; for (s = 1; s < arguments.length; ++s) { source = Object(arguments[s]); props = keys(source); if (hasSymbols && Object.getOwnPropertySymbols) { props.push.apply(props, Object.getOwnPropertySymbols(source).filter(isEnumerableOn(source))); } for (i = 0; i < props.length; ++i) { objTarget[props[i]] = source[props[i]]; } } return objTarget; }; assignShim.shim = function shimObjectAssign() { if (Object.assign && Object.preventExtensions) { var assignHasPendingExceptions = (function () { // Firefox 37 still has "pending exception" logic in its Object.assign implementation, // which is 72% slower than our shim, and Firefox 40's native implementation. var thrower = Object.preventExtensions({ 1: 2 }); try { Object.assign(thrower, 'xy'); } catch (e) { return thrower[1] === 'y'; } }()); if (assignHasPendingExceptions) { delete Object.assign; } } if (!Object.assign) { defineProperties(Object, { assign: assignShim }); } return Object.assign || assignShim; }; module.exports = assignShim; },{"define-properties":45,"object-keys":47}],45:[function(_dereq_,module,exports){ 'use strict'; var keys = _dereq_('object-keys'); var foreach = _dereq_('foreach'); var toStr = Object.prototype.toString; var isFunction = function (fn) { return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; }; var arePropertyDescriptorsSupported = function () { var obj = {}; try { Object.defineProperty(obj, 'x', { value: obj }); return obj.x === obj; } catch (e) { /* this is IE 8. */ return false; } }; var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported(); var defineProperty = function (object, name, value, predicate) { if (name in object && (!isFunction(predicate) || !predicate())) { return; } if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: value }); } else { object[name] = value; } }; var defineProperties = function (object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; foreach(keys(map), function (name) { defineProperty(object, name, map[name], predicates[name]); }); }; defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; },{"foreach":46,"object-keys":47}],46:[function(_dereq_,module,exports){ var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; module.exports = function forEach (obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; },{}],47:[function(_dereq_,module,exports){ 'use strict'; // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var isArgs = _dereq_('./isArguments'); var hasDontEnumBug = !({ 'toString': null }).propertyIsEnumerable('toString'); var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var ctor = object.constructor; var skipConstructor = ctor && ctor.prototype === object; for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (!Object.keys) { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; },{"./isArguments":48}],48:[function(_dereq_,module,exports){ 'use strict'; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; },{}],49:[function(_dereq_,module,exports){ module.exports = SafeParseTuple function SafeParseTuple(obj, reviver) { var json var error = null try { json = JSON.parse(obj, reviver) } catch (err) { error = err } return [error, json] } },{}],50:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file big-play-button.js */ var _Button2 = _dereq_('./button.js'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('./component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * Initial play button. Shows before the video has played. The hiding of the * big play button is done via CSS and player states. * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Button * @class BigPlayButton */ var BigPlayButton = (function (_Button) { function BigPlayButton(player, options) { _classCallCheck(this, BigPlayButton); _Button.call(this, player, options); } _inherits(BigPlayButton, _Button); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ BigPlayButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-big-play-button'; }; /** * Handles click for play * * @method handleClick */ BigPlayButton.prototype.handleClick = function handleClick() { this.player_.play(); }; return BigPlayButton; })(_Button3['default']); BigPlayButton.prototype.controlText_ = 'Play Video'; _Component2['default'].registerComponent('BigPlayButton', BigPlayButton); exports['default'] = BigPlayButton; module.exports = exports['default']; },{"./button.js":51,"./component.js":52}],51:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file button.js */ var _Component2 = _dereq_('./component'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_import2); var _import3 = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_import3); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); /** * Base class for all buttons * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class Button */ var Button = (function (_Component) { function Button(player, options) { _classCallCheck(this, Button); _Component.call(this, player, options); this.emitTapEvents(); this.on('tap', this.handleClick); this.on('click', this.handleClick); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); } _inherits(Button, _Component); /** * Create the component's DOM element * * @param {String=} type Element's node type. e.g. 'div' * @param {Object=} props An object of element attributes that should be set on the element Tag name * @return {Element} * @method createEl */ Button.prototype.createEl = function createEl() { var type = arguments[0] === undefined ? 'button' : arguments[0]; var props = arguments[1] === undefined ? {} : arguments[1]; // Add standard Aria and Tabindex info props = _assign2['default']({ className: this.buildCSSClass(), role: 'button', 'aria-live': 'polite', // let the screen reader user know that the text of the button may change tabIndex: 0 }, props); var el = _Component.prototype.createEl.call(this, type, props); this.controlTextEl_ = Dom.createEl('span', { className: 'vjs-control-text' }); el.appendChild(this.controlTextEl_); this.controlText(this.controlText_); return el; }; /** * Controls text - both request and localize * * @param {String} text Text for button * @return {String} * @method controlText */ Button.prototype.controlText = function controlText(text) { if (!text) { return this.controlText_ || 'Need Text'; }this.controlText_ = text; this.controlTextEl_.innerHTML = this.localize(this.controlText_); return this; }; /** * Allows sub components to stack CSS class names * * @return {String} * @method buildCSSClass */ Button.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-control vjs-button ' + _Component.prototype.buildCSSClass.call(this); }; /** * Handle Click - Override with specific functionality for button * * @method handleClick */ Button.prototype.handleClick = function handleClick() {}; /** * Handle Focus - Add keyboard functionality to element * * @method handleFocus */ Button.prototype.handleFocus = function handleFocus() { Events.on(_document2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; /** * Handle KeyPress (document level) - Trigger click when keys are pressed * * @method handleKeyPress */ Button.prototype.handleKeyPress = function handleKeyPress(event) { // Check for space bar (32) or enter (13) keys if (event.which === 32 || event.which === 13) { event.preventDefault(); this.handleClick(); } }; /** * Handle Blur - Remove keyboard triggers * * @method handleBlur */ Button.prototype.handleBlur = function handleBlur() { Events.off(_document2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; return Button; })(_Component3['default']); _Component3['default'].registerComponent('Button', Button); exports['default'] = Button; module.exports = exports['default']; },{"./component":52,"./utils/dom.js":111,"./utils/events.js":112,"./utils/fn.js":113,"global/document":1,"object.assign":44}],52:[function(_dereq_,module,exports){ '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; /** * @file component.js * * Player Component - Base class for all UI objects */ var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _import = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_import2); var _import3 = _dereq_('./utils/guid.js'); var Guid = _interopRequireWildcard(_import3); var _import4 = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_import4); var _log = _dereq_('./utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _toTitleCase = _dereq_('./utils/to-title-case.js'); var _toTitleCase2 = _interopRequireWildcard(_toTitleCase); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); var _mergeOptions = _dereq_('./utils/merge-options.js'); var _mergeOptions2 = _interopRequireWildcard(_mergeOptions); /** * Base UI Component class * Components are embeddable UI objects that are represented by both a * javascript object and an element in the DOM. They can be children of other * components, and can have many children themselves. * ```js * // adding a button to the player * var button = player.addChild('button'); * button.el(); // -> button element * ``` * ```html * <div class="video-js"> * <div class="vjs-button">Button</div> * </div> * ``` * Components are also event targets. * ```js * button.on('click', function(){ * console.log('Button Clicked!'); * }); * button.trigger('customevent'); * ``` * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @class Component */ var Component = (function () { function Component(player, options, ready) { _classCallCheck(this, Component); // The component might be the player itself and we can't pass `this` to super if (!player && this.play) { this.player_ = player = this; // eslint-disable-line } else { this.player_ = player; } // Make a copy of prototype.options_ to protect against overriding defaults this.options_ = _mergeOptions2['default']({}, this.options_); // Updated options with supplied options options = this.options_ = _mergeOptions2['default'](this.options_, options); // Get ID from options or options element if one is supplied this.id_ = options.id || options.el && options.el.id; // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players var id = player && player.id && player.id() || 'no_player'; this.id_ = '' + id + '_component_' + Guid.newGUID(); } this.name_ = options.name || null; // Create element if one wasn't provided in options if (options.el) { this.el_ = options.el; } else if (options.createEl !== false) { this.el_ = this.createEl(); } this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options if (options.initChildren !== false) { this.initChildren(); } this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } // Temp for ES6 class transition, remove before 5.0 Component.prototype.init = function init() { // console.log('init called on Component'); Component.apply(this, arguments); }; /** * Dispose of the component and all child components * * @method dispose */ Component.prototype.dispose = function dispose() { this.trigger({ type: 'dispose', bubbles: false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; // Remove all event listeners. this.off(); // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } Dom.removeElData(this.el_); this.el_ = null; }; /** * Return the component's player * * @return {Player} * @method player */ Component.prototype.player = function player() { return this.player_; }; /** * Deep merge of options objects * Whenever a property is an object on both options objects * the two properties will be merged using mergeOptions. * This is used for merging options for child components. We * want it to be easy to override individual options on a child * component without having to rewrite all the other default options. * ```js * Parent.prototype.options_ = { * children: { * 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' }, * 'childTwo': {}, * 'childThree': {} * } * } * newOptions = { * children: { * 'childOne': { 'foo': 'baz', 'abc': '123' } * 'childTwo': null, * 'childFour': {} * } * } * * this.options(newOptions); * ``` * RESULT * ```js * { * children: { * 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' }, * 'childTwo': null, // Disabled. Won't be initialized. * 'childThree': {}, * 'childFour': {} * } * } * ``` * * @param {Object} obj Object of new option values * @return {Object} A NEW object of this.options_ and obj merged * @method options */ Component.prototype.options = function options(obj) { _log2['default'].warn('this.options() has been deprecated and will be moved to the constructor in 6.0'); if (!obj) { return this.options_; } this.options_ = _mergeOptions2['default'](this.options_, obj); return this.options_; }; /** * Get the component's DOM element * ```js * var domEl = myComponent.el(); * ``` * * @return {Element} * @method el */ Component.prototype.el = function el() { return this.el_; }; /** * Create the component's DOM element * * @param {String=} tagName Element's node type. e.g. 'div' * @param {Object=} attributes An object of element attributes that should be set on the element * @return {Element} * @method createEl */ Component.prototype.createEl = function createEl(tagName, attributes) { return Dom.createEl(tagName, attributes); }; Component.prototype.localize = function localize(string) { var code = this.player_.language && this.player_.language(); var languages = this.player_.languages && this.player_.languages(); if (!code || !languages) { return string; } var language = languages[code]; if (language && language[string]) { return language[string]; } var primaryCode = code.split('-')[0]; var primaryLang = languages[primaryCode]; if (primaryLang && primaryLang[string]) { return primaryLang[string]; } return string; }; /** * Return the component's DOM element where children are inserted. * Will either be the same as el() or a new element defined in createEl(). * * @return {Element} * @method contentEl */ Component.prototype.contentEl = function contentEl() { return this.contentEl_ || this.el_; }; /** * Get the component's ID * ```js * var id = myComponent.id(); * ``` * * @return {String} * @method id */ Component.prototype.id = function id() { return this.id_; }; /** * Get the component's name. The name is often used to reference the component. * ```js * var name = myComponent.name(); * ``` * * @return {String} * @method name */ Component.prototype.name = function name() { return this.name_; }; /** * Get an array of all child components * ```js * var kids = myComponent.children(); * ``` * * @return {Array} The children * @method children */ Component.prototype.children = function children() { return this.children_; }; /** * Returns a child component with the provided ID * * @return {Component} * @method getChildById */ Component.prototype.getChildById = function getChildById(id) { return this.childIndex_[id]; }; /** * Returns a child component with the provided name * * @return {Component} * @method getChild */ Component.prototype.getChild = function getChild(name) { return this.childNameIndex_[name]; }; /** * Adds a child component inside this component * ```js * myComponent.el(); * // -> <div class='my-component'></div> * myComponent.children(); * // [empty array] * * var myButton = myComponent.addChild('MyButton'); * // -> <div class='my-component'><div class="my-button">myButton<div></div> * // -> myButton === myComonent.children()[0]; * ``` * Pass in options for child constructors and options for children of the child * ```js * var myButton = myComponent.addChild('MyButton', { * text: 'Press Me', * children: { * buttonChildExample: { * buttonChildOption: true * } * } * }); * ``` * * @param {String|Component} child The class name or instance of a child to add * @param {Object=} options Options, including options to be passed to children of the child. * @return {Component} The child component (created by this process if a string was used) * @method addChild */ Component.prototype.addChild = function addChild(child) { var options = arguments[1] === undefined ? {} : arguments[1]; var component = undefined; var componentName = undefined; // If child is a string, create nt with options if (typeof child === 'string') { componentName = child; // Options can also be specified as a boolean, so convert to an empty object if false. if (!options) { options = {}; } // Same as above, but true is deprecated so show a warning. if (options === true) { _log2['default'].warn('Initializing a child component with `true` is deprecated. Children should be defined in an array when possible, but if necessary use an object instead of `true`.'); options = {}; } // If no componentClass in options, assume componentClass is the name lowercased // (e.g. playButton) var componentClassName = options.componentClass || _toTitleCase2['default'](componentName); // Set name through options options.name = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player var ComponentClass = Component.getComponent(componentClassName); component = new ComponentClass(this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.push(component); if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || component.name && component.name(); if (componentName) { this.childNameIndex_[componentName] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component.el === 'function' && component.el()) { this.contentEl().appendChild(component.el()); } // Return so it can stored on parent object if desired. return component; }; /** * Remove a child component from this component's list of children, and the * child component's element from this component's element * * @param {Component} component Component to remove * @method removeChild */ Component.prototype.removeChild = function removeChild(component) { if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) { return; } var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i, 1); break; } } if (!childFound) { return; } this.childIndex_[component.id()] = null; this.childNameIndex_[component.name()] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } }; /** * Add and initialize default child components from options * ```js * // when an instance of MyComponent is created, all children in options * // will be added to the instance by their name strings and options * MyComponent.prototype.options_.children = { * myChildComponent: { * myChildOption: true * } * } * ``` * // Or when creating the component * ```js * var myComp = new MyComponent(player, { * children: { * myChildComponent: { * myChildOption: true * } * } * }); * ``` * The children option can also be an Array of child names or * child options objects (that also include a 'name' key). * ```js * var myComp = new MyComponent(player, { * children: [ * 'button', * { * name: 'button', * someOtherOption: true * } * ] * }); * ``` * * @method initChildren */ Component.prototype.initChildren = function initChildren() { var _this = this; var children = this.options_.children; if (children) { (function () { // `this` is `parent` var parentOptions = _this.options_; var handleAdd = function handleAdd(name, opts) { // Allow options for children to be set at the parent options // e.g. videojs(id, { controlBar: false }); // instead of videojs(id, { children: { controlBar: false }); if (parentOptions[name] !== undefined) { opts = parentOptions[name]; } // Allow for disabling default components // e.g. options['children']['posterImage'] = false if (opts === false) { return; } // We also want to pass the original player options to each component as well so they don't need to // reach back into the player for options later. opts.playerOptions = _this.options_.playerOptions; // Create and add the child component. // Add a direct reference to the child by name on the parent instance. // If two of the same component are used, different names should be supplied // for each _this[name] = _this.addChild(name, opts); }; // Allow for an array of children details to passed in the options if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var child = children[i]; var _name = undefined; var opts = undefined; if (typeof child === 'string') { // ['myComponent'] _name = child; opts = {}; } else { // [{ name: 'myComponent', otherOption: true }] _name = child.name; opts = child; } handleAdd(_name, opts); } } else { Object.getOwnPropertyNames(children).forEach(function (name) { handleAdd(name, children[name]); }); } })(); } }; /** * Allows sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ Component.prototype.buildCSSClass = function buildCSSClass() { // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /** * Add an event listener to this component's element * ```js * var myFunc = function(){ * var myComponent = this; * // Do something when the event is fired * }; * * myComponent.on('eventType', myFunc); * ``` * The context of myFunc will be myComponent unless previously bound. * Alternatively, you can add a listener to another element or component. * ```js * myComponent.on(otherElement, 'eventName', myFunc); * myComponent.on(otherComponent, 'eventName', myFunc); * ``` * The benefit of using this over `VjsEvents.on(otherElement, 'eventName', myFunc)` * and `otherComponent.on('eventName', myFunc)` is that this way the listeners * will be automatically cleaned up when either component is disposed. * It will also bind myComponent as the context of myFunc. * **NOTE**: When using this on elements in the page other than window * and document (both permanent), if you remove the element from the DOM * you need to call `myComponent.trigger(el, 'dispose')` on it to clean up * references to it and allow the browser to garbage collect it. * * @param {String|Component} first The event type or other component * @param {Function|String} second The event handler or event type * @param {Function} third The event handler * @return {Component} * @method on */ Component.prototype.on = function on(first, second, third) { var _this2 = this; if (typeof first === 'string' || Array.isArray(first)) { Events.on(this.el_, first, Fn.bind(this, second)); // Targeting another component or element } else { (function () { var target = first; var type = second; var fn = Fn.bind(_this2, third); // When this component is disposed, remove the listener from the other component var removeOnDispose = function removeOnDispose() { return _this2.off(target, type, fn); }; // Use the same function ID so we can remove it later it using the ID // of the original listener removeOnDispose.guid = fn.guid; _this2.on('dispose', removeOnDispose); // If the other component is disposed first we need to clean the reference // to the other component in this component's removeOnDispose listener // Otherwise we create a memory leak. var cleanRemover = function cleanRemover() { return _this2.off('dispose', removeOnDispose); }; // Add the same function ID so we can easily remove it later cleanRemover.guid = fn.guid; // Check if this is a DOM node if (first.nodeName) { // Add the listener to the other element Events.on(target, type, fn); Events.on(target, 'dispose', cleanRemover); // Should be a component // Not using `instanceof Component` because it makes mock players difficult } else if (typeof first.on === 'function') { // Add the listener to the other component target.on(type, fn); target.on('dispose', cleanRemover); } })(); } return this; }; /** * Remove an event listener from this component's element * ```js * myComponent.off('eventType', myFunc); * ``` * If myFunc is excluded, ALL listeners for the event type will be removed. * If eventType is excluded, ALL listeners will be removed from the component. * Alternatively you can use `off` to remove listeners that were added to other * elements or components using `myComponent.on(otherComponent...`. * In this case both the event type and listener function are REQUIRED. * ```js * myComponent.off(otherElement, 'eventType', myFunc); * myComponent.off(otherComponent, 'eventType', myFunc); * ``` * * @param {String=|Component} first The event type or other component * @param {Function=|String} second The listener function or event type * @param {Function=} third The listener for other component * @return {Component} * @method off */ Component.prototype.off = function off(first, second, third) { if (!first || typeof first === 'string' || Array.isArray(first)) { Events.off(this.el_, first, second); } else { var target = first; var type = second; // Ensure there's at least a guid, even if the function hasn't been used var fn = Fn.bind(this, third); // Remove the dispose listener on this component, // which was given the same guid as the event listener this.off('dispose', fn); if (first.nodeName) { // Remove the listener Events.off(target, type, fn); // Remove the listener for cleaning the dispose listener Events.off(target, 'dispose', fn); } else { target.off(type, fn); target.off('dispose', fn); } } return this; }; /** * Add an event listener to be triggered only once and then removed * ```js * myComponent.one('eventName', myFunc); * ``` * Alternatively you can add a listener to another element or component * that will be triggered only once. * ```js * myComponent.one(otherElement, 'eventName', myFunc); * myComponent.one(otherComponent, 'eventName', myFunc); * ``` * * @param {String|Component} first The event type or other component * @param {Function|String} second The listener function or event type * @param {Function=} third The listener function for other component * @return {Component} * @method one */ Component.prototype.one = function one(first, second, third) { var _this3 = this; var _arguments = arguments; if (typeof first === 'string' || Array.isArray(first)) { Events.one(this.el_, first, Fn.bind(this, second)); } else { (function () { var target = first; var type = second; var fn = Fn.bind(_this3, third); var newFunc = (function (_newFunc) { function newFunc() { return _newFunc.apply(this, arguments); } newFunc.toString = function () { return _newFunc.toString(); }; return newFunc; })(function () { _this3.off(target, type, newFunc); fn.apply(null, _arguments); }); // Keep the same function ID so we can remove it later newFunc.guid = fn.guid; _this3.on(target, type, newFunc); })(); } return this; }; /** * Trigger an event on an element * ```js * myComponent.trigger('eventName'); * myComponent.trigger({'type':'eventName'}); * myComponent.trigger('eventName', {data: 'some data'}); * myComponent.trigger({'type':'eventName'}, {data: 'some data'}); * ``` * * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Component} self * @method trigger */ Component.prototype.trigger = function trigger(event, hash) { Events.trigger(this.el_, event, hash); return this; }; /** * Bind a listener to the component's ready state. * Different from event listeners in that if the ready event has already happened * it will trigger the function immediately. * * @param {Function} fn Ready listener * @return {Component} * @method ready */ Component.prototype.ready = function ready(fn) { if (fn) { if (this.isReady_) { // Ensure function is always called asynchronously this.setTimeout(fn, 1); } else { this.readyQueue_ = this.readyQueue_ || []; this.readyQueue_.push(fn); } } return this; }; /** * Trigger the ready listeners * * @return {Component} * @method triggerReady */ Component.prototype.triggerReady = function triggerReady() { this.isReady_ = true; // Ensure ready is triggerd asynchronously this.setTimeout(function () { var readyQueue = this.readyQueue_; if (readyQueue && readyQueue.length > 0) { readyQueue.forEach(function (fn) { fn.call(this); }, this); // Reset Ready Queue this.readyQueue_ = []; } // Allow for using event listeners also this.trigger('ready'); }, 1); }; /** * Check if a component's element has a CSS class name * * @param {String} classToCheck Classname to check * @return {Component} * @method hasClass */ Component.prototype.hasClass = function hasClass(classToCheck) { return Dom.hasElClass(this.el_, classToCheck); }; /** * Add a CSS class name to the component's element * * @param {String} classToAdd Classname to add * @return {Component} * @method addClass */ Component.prototype.addClass = function addClass(classToAdd) { Dom.addElClass(this.el_, classToAdd); return this; }; /** * Remove and return a CSS class name from the component's element * * @param {String} classToRemove Classname to remove * @return {Component} * @method removeClass */ Component.prototype.removeClass = function removeClass(classToRemove) { Dom.removeElClass(this.el_, classToRemove); return this; }; /** * Show the component element if hidden * * @return {Component} * @method show */ Component.prototype.show = function show() { this.removeClass('vjs-hidden'); return this; }; /** * Hide the component element if currently showing * * @return {Component} * @method hide */ Component.prototype.hide = function hide() { this.addClass('vjs-hidden'); return this; }; /** * Lock an item in its visible state * To be used with fadeIn/fadeOut. * * @return {Component} * @private * @method lockShowing */ Component.prototype.lockShowing = function lockShowing() { this.addClass('vjs-lock-showing'); return this; }; /** * Unlock an item to be hidden * To be used with fadeIn/fadeOut. * * @return {Component} * @private * @method unlockShowing */ Component.prototype.unlockShowing = function unlockShowing() { this.removeClass('vjs-lock-showing'); return this; }; /** * Set or get the width of the component (CSS values) * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num Optional width number * @param {Boolean} skipListeners Skip the 'resize' event trigger * @return {Component} This component, when setting the width * @return {Number|String} The width, when getting * @method width */ Component.prototype.width = function width(num, skipListeners) { return this.dimension('width', num, skipListeners); }; /** * Get or set the height of the component (CSS values) * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num New component height * @param {Boolean=} skipListeners Skip the resize event trigger * @return {Component} This component, when setting the height * @return {Number|String} The height, when getting * @method height */ Component.prototype.height = function height(num, skipListeners) { return this.dimension('height', num, skipListeners); }; /** * Set both width and height at the same time * * @param {Number|String} width Width of player * @param {Number|String} height Height of player * @return {Component} The component * @method dimensions */ Component.prototype.dimensions = function dimensions(width, height) { // Skip resize listeners on width for optimization return this.width(width, true).height(height); }; /** * Get or set width or height * This is the shared code for the width() and height() methods. * All for an integer, integer + 'px' or integer + '%'; * Known issue: Hidden elements officially have a width of 0. We're defaulting * to the style.width value and falling back to computedStyle which has the * hidden element issue. Info, but probably not an efficient fix: * http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/ * * @param {String} widthOrHeight 'width' or 'height' * @param {Number|String=} num New dimension * @param {Boolean=} skipListeners Skip resize event trigger * @return {Component} The component if a dimension was set * @return {Number|String} The dimension if nothing was set * @private * @method dimension */ Component.prototype.dimension = function dimension(widthOrHeight, num, skipListeners) { if (num !== undefined) { // Set to zero if null or literally NaN (NaN !== NaN) if (num === null || num !== num) { num = 0; } // Check if using css width/height (% or px) and adjust if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num + 'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { this.trigger('resize'); } // Return component return this; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) { return 0; } // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0, pxIndex), 10); } // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px return parseInt(this.el_['offset' + _toTitleCase2['default'](widthOrHeight)], 10); }; /** * Emit 'tap' events when touch events are supported * This is used to support toggling the controls through a tap on the video. * We're requiring them to be enabled because otherwise every component would * have this extra overhead unnecessarily, on mobile devices where extra * overhead is especially bad. * * @private * @method emitTapEvents */ Component.prototype.emitTapEvents = function emitTapEvents() { // Track the start time so we can determine how long the touch lasted var touchStart = 0; var firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap // Other popular libs use anywhere from 2 (hammer.js) to 15, so 10 seems like a nice, round number. var tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap var touchTimeThreshold = 200; var couldBeTap = undefined; this.on('touchstart', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { // Copy the touches object to prevent modifying the original firstTouch = _assign2['default']({}, event.touches[0]); // Record start time so we can detect a tap vs. "touch and hold" touchStart = new Date().getTime(); // Reset couldBeTap tracking couldBeTap = true; } }); this.on('touchmove', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length > 1) { couldBeTap = false; } else if (firstTouch) { // Some devices will throw touchmoves for all but the slightest of taps. // So, if we moved only a small distance, this could still be a tap var xdiff = event.touches[0].pageX - firstTouch.pageX; var ydiff = event.touches[0].pageY - firstTouch.pageY; var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); var noTap = function noTap() { couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function (event) { firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted var touchTime = new Date().getTime() - touchStart; // Make sure the touch was less than the threshold to be considered a tap if (touchTime < touchTimeThreshold) { // Don't let browser turn this into a click event.preventDefault(); this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // Events.fixEvent runs (e.g. event.target) } } }); }; /** * Report user touch activity when touch events occur * User activity is used to determine when controls should show/hide. It's * relatively simple when it comes to mouse events, because any mouse event * should show the controls. So we capture mouse events that bubble up to the * player and report activity when that happens. * With touch events it isn't as easy. We can't rely on touch events at the * player level, because a tap (touchstart + touchend) on the video itself on * mobile devices is meant to turn controls off (and on). User activity is * checked asynchronously, so what could happen is a tap event on the video * turns the controls off, then the touchend event bubbles up to the player, * which if it reported user activity, would turn the controls right back on. * (We also don't want to completely block touch events from bubbling up) * Also a touchmove, touch+hold, and anything other than a tap is not supposed * to turn the controls back on on a mobile device. * Here we're setting the default component behavior to report user activity * whenever touch events happen, and this can be turned off by components that * want touch events to act differently. * * @method enableTouchActivity */ Component.prototype.enableTouchActivity = function enableTouchActivity() { // Don't continue if the root player doesn't support reporting user activity if (!this.player() || !this.player().reportUserActivity) { return; } // listener for reporting that the user is active var report = Fn.bind(this.player(), this.player().reportUserActivity); var touchHolding = undefined; this.on('touchstart', function () { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = this.setInterval(report, 250); }); var touchEnd = function touchEnd(event) { report(); // stop the interval that maintains activity if the touch is holding this.clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /** * Creates timeout and sets up disposal automatically. * * @param {Function} fn The function to run after the timeout. * @param {Number} timeout Number of ms to delay before executing specified function. * @return {Number} Returns the timeout ID * @method setTimeout */ Component.prototype.setTimeout = function setTimeout(fn, timeout) { fn = Fn.bind(this, fn); // window.setTimeout would be preferable here, but due to some bizarre issue with Sinon and/or Phantomjs, we can't. var timeoutId = _window2['default'].setTimeout(fn, timeout); var disposeFn = function disposeFn() { this.clearTimeout(timeoutId); }; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.on('dispose', disposeFn); return timeoutId; }; /** * Clears a timeout and removes the associated dispose listener * * @param {Number} timeoutId The id of the timeout to clear * @return {Number} Returns the timeout ID * @method clearTimeout */ Component.prototype.clearTimeout = function clearTimeout(timeoutId) { _window2['default'].clearTimeout(timeoutId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.off('dispose', disposeFn); return timeoutId; }; /** * Creates an interval and sets up disposal automatically. * * @param {Function} fn The function to run every N seconds. * @param {Number} interval Number of ms to delay before executing specified function. * @return {Number} Returns the interval ID * @method setInterval */ Component.prototype.setInterval = function setInterval(fn, interval) { fn = Fn.bind(this, fn); var intervalId = _window2['default'].setInterval(fn, interval); var disposeFn = function disposeFn() { this.clearInterval(intervalId); }; disposeFn.guid = 'vjs-interval-' + intervalId; this.on('dispose', disposeFn); return intervalId; }; /** * Clears an interval and removes the associated dispose listener * * @param {Number} intervalId The id of the interval to clear * @return {Number} Returns the interval ID * @method clearInterval */ Component.prototype.clearInterval = function clearInterval(intervalId) { _window2['default'].clearInterval(intervalId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-interval-' + intervalId; this.off('dispose', disposeFn); return intervalId; }; /** * Registers a component * * @param {String} name Name of the component to register * @param {Object} comp The component to register * @static * @method registerComponent */ Component.registerComponent = function registerComponent(name, comp) { if (!Component.components_) { Component.components_ = {}; } Component.components_[name] = comp; return comp; }; /** * Gets a component by name * * @param {String} name Name of the component to get * @return {Component} * @static * @method getComponent */ Component.getComponent = function getComponent(name) { if (Component.components_ && Component.components_[name]) { return Component.components_[name]; } if (_window2['default'] && _window2['default'].videojs && _window2['default'].videojs[name]) { _log2['default'].warn('The ' + name + ' component was added to the videojs object when it should be registered using videojs.registerComponent(name, component)'); return _window2['default'].videojs[name]; } }; /** * Sets up the constructor using the supplied init method * or uses the init of the parent object * * @param {Object} props An object of properties * @static * @deprecated * @method extend */ Component.extend = function extend(props) { props = props || {}; _log2['default'].warn('Component.extend({}) has been deprecated, use videojs.extends(Component, {}) instead'); // Set up the constructor using the supplied init method // or using the init of the parent object // Make sure to check the unobfuscated version for external libs var init = props.init || props.init || this.prototype.init || this.prototype.init || function () {}; // In Resig's simple class inheritance (previously used) the constructor // is a function that calls `this.init.apply(arguments)` // However that would prevent us from using `ParentObject.call(this);` // in a Child constructor because the `this` in `this.init` // would still refer to the Child and cause an infinite loop. // We would instead have to do // `ParentObject.prototype.init.apply(this, arguments);` // Bleh. We're not creating a _super() function, so it's good to keep // the parent constructor reference simple. var subObj = function subObj() { init.apply(this, arguments); }; // Inherit from this object's prototype subObj.prototype = Object.create(this.prototype); // Reset the constructor property for subObj otherwise // instances of subObj would have the constructor of the parent Object subObj.prototype.constructor = subObj; // Make the class extendable subObj.extend = Component.extend; // Extend subObj's prototype with functions and other properties from props for (var _name2 in props) { if (props.hasOwnProperty(_name2)) { subObj.prototype[_name2] = props[_name2]; } } return subObj; }; return Component; })(); Component.registerComponent('Component', Component); exports['default'] = Component; module.exports = exports['default']; },{"./utils/dom.js":111,"./utils/events.js":112,"./utils/fn.js":113,"./utils/guid.js":115,"./utils/log.js":116,"./utils/merge-options.js":117,"./utils/to-title-case.js":119,"global/window":2,"object.assign":44}],53:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file control-bar.js */ var _Component2 = _dereq_('../component.js'); var _Component3 = _interopRequireWildcard(_Component2); // Required children var _PlayToggle = _dereq_('./play-toggle.js'); var _PlayToggle2 = _interopRequireWildcard(_PlayToggle); var _CurrentTimeDisplay = _dereq_('./time-controls/current-time-display.js'); var _CurrentTimeDisplay2 = _interopRequireWildcard(_CurrentTimeDisplay); var _DurationDisplay = _dereq_('./time-controls/duration-display.js'); var _DurationDisplay2 = _interopRequireWildcard(_DurationDisplay); var _TimeDivider = _dereq_('./time-controls/time-divider.js'); var _TimeDivider2 = _interopRequireWildcard(_TimeDivider); var _RemainingTimeDisplay = _dereq_('./time-controls/remaining-time-display.js'); var _RemainingTimeDisplay2 = _interopRequireWildcard(_RemainingTimeDisplay); var _LiveDisplay = _dereq_('./live-display.js'); var _LiveDisplay2 = _interopRequireWildcard(_LiveDisplay); var _ProgressControl = _dereq_('./progress-control/progress-control.js'); var _ProgressControl2 = _interopRequireWildcard(_ProgressControl); var _FullscreenToggle = _dereq_('./fullscreen-toggle.js'); var _FullscreenToggle2 = _interopRequireWildcard(_FullscreenToggle); var _VolumeControl = _dereq_('./volume-control/volume-control.js'); var _VolumeControl2 = _interopRequireWildcard(_VolumeControl); var _VolumeMenuButton = _dereq_('./volume-menu-button.js'); var _VolumeMenuButton2 = _interopRequireWildcard(_VolumeMenuButton); var _MuteToggle = _dereq_('./mute-toggle.js'); var _MuteToggle2 = _interopRequireWildcard(_MuteToggle); var _ChaptersButton = _dereq_('./text-track-controls/chapters-button.js'); var _ChaptersButton2 = _interopRequireWildcard(_ChaptersButton); var _SubtitlesButton = _dereq_('./text-track-controls/subtitles-button.js'); var _SubtitlesButton2 = _interopRequireWildcard(_SubtitlesButton); var _CaptionsButton = _dereq_('./text-track-controls/captions-button.js'); var _CaptionsButton2 = _interopRequireWildcard(_CaptionsButton); var _PlaybackRateMenuButton = _dereq_('./playback-rate-menu/playback-rate-menu-button.js'); var _PlaybackRateMenuButton2 = _interopRequireWildcard(_PlaybackRateMenuButton); var _CustomControlSpacer = _dereq_('./spacer-controls/custom-control-spacer.js'); var _CustomControlSpacer2 = _interopRequireWildcard(_CustomControlSpacer); /** * Container of main controls * * @extends Component * @class ControlBar */ var ControlBar = (function (_Component) { function ControlBar() { _classCallCheck(this, ControlBar); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(ControlBar, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ ControlBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-control-bar' }); }; return ControlBar; })(_Component3['default']); ControlBar.prototype.options_ = { loadEvent: 'play', children: ['playToggle', 'volumeMenuButton', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'muteToggle', 'volumeControl', 'chaptersButton', 'subtitlesButton', 'captionsButton', 'fullscreenToggle'] }; _Component3['default'].registerComponent('ControlBar', ControlBar); exports['default'] = ControlBar; module.exports = exports['default']; },{"../component.js":52,"./fullscreen-toggle.js":54,"./live-display.js":55,"./mute-toggle.js":56,"./play-toggle.js":57,"./playback-rate-menu/playback-rate-menu-button.js":58,"./progress-control/progress-control.js":62,"./spacer-controls/custom-control-spacer.js":64,"./text-track-controls/captions-button.js":67,"./text-track-controls/chapters-button.js":68,"./text-track-controls/subtitles-button.js":71,"./time-controls/current-time-display.js":74,"./time-controls/duration-display.js":75,"./time-controls/remaining-time-display.js":76,"./time-controls/time-divider.js":77,"./volume-control/volume-control.js":79,"./volume-menu-button.js":81}],54:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file fullscreen-toggle.js */ var _Button2 = _dereq_('../button.js'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * Toggle fullscreen video * * @extends Button * @class FullscreenToggle */ var FullscreenToggle = (function (_Button) { function FullscreenToggle() { _classCallCheck(this, FullscreenToggle); if (_Button != null) { _Button.apply(this, arguments); } } _inherits(FullscreenToggle, _Button); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ FullscreenToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-fullscreen-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handles click for full screen * * @method handleClick */ FullscreenToggle.prototype.handleClick = function handleClick() { if (!this.player_.isFullscreen()) { this.player_.requestFullscreen(); this.controlText('Non-Fullscreen'); } else { this.player_.exitFullscreen(); this.controlText('Fullscreen'); } }; return FullscreenToggle; })(_Button3['default']); FullscreenToggle.prototype.controlText_ = 'Fullscreen'; _Component2['default'].registerComponent('FullscreenToggle', FullscreenToggle); exports['default'] = FullscreenToggle; module.exports = exports['default']; },{"../button.js":51,"../component.js":52}],55:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file live-display.js */ var _Component2 = _dereq_('../component'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); /** * Displays the live indicator * TODO - Future make it click to snap to live * * @extends Component * @class LiveDisplay */ var LiveDisplay = (function (_Component) { function LiveDisplay() { _classCallCheck(this, LiveDisplay); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(LiveDisplay, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ LiveDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-live-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-live-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE'), 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; return LiveDisplay; })(_Component3['default']); _Component3['default'].registerComponent('LiveDisplay', LiveDisplay); exports['default'] = LiveDisplay; module.exports = exports['default']; },{"../component":52,"../utils/dom.js":111}],56:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file mute-toggle.js */ var _Button2 = _dereq_('../button'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('../component'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); /** * A button component for muting the audio * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MuteToggle */ var MuteToggle = (function (_Button) { function MuteToggle(player, options) { _classCallCheck(this, MuteToggle); _Button.call(this, player, options); this.on(player, 'volumechange', this.update); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { if (player.tech.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } _inherits(MuteToggle, _Button); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ MuteToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-mute-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handle click on mute * * @method handleClick */ MuteToggle.prototype.handleClick = function handleClick() { this.player_.muted(this.player_.muted() ? false : true); }; /** * Update volume * * @method update */ MuteToggle.prototype.update = function update() { var vol = this.player_.volume(), level = 3; if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // Don't rewrite the button text if the actual text doesn't change. // This causes unnecessary and confusing information for screen reader users. // This check is needed because this function gets called every time the volume level is changed. var toMute = this.player_.muted() ? 'Unmute' : 'Mute'; var localizedMute = this.localize(toMute); if (this.controlText() !== localizedMute) { this.controlText(localizedMute); } /* TODO improve muted icon classes */ for (var i = 0; i < 4; i++) { Dom.removeElClass(this.el_, 'vjs-vol-' + i); } Dom.addElClass(this.el_, 'vjs-vol-' + level); }; return MuteToggle; })(_Button3['default']); MuteToggle.prototype.controlText_ = 'Mute'; _Component2['default'].registerComponent('MuteToggle', MuteToggle); exports['default'] = MuteToggle; module.exports = exports['default']; },{"../button":51,"../component":52,"../utils/dom.js":111}],57:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file play-toggle.js */ var _Button2 = _dereq_('../button.js'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * Button to toggle between play and pause * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class PlayToggle */ var PlayToggle = (function (_Button) { function PlayToggle(player, options) { _classCallCheck(this, PlayToggle); _Button.call(this, player, options); this.on(player, 'play', this.handlePlay); this.on(player, 'pause', this.handlePause); } _inherits(PlayToggle, _Button); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ PlayToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-play-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handle click to toggle between play and pause * * @method handleClick */ PlayToggle.prototype.handleClick = function handleClick() { if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; /** * Add the vjs-playing class to the element so it can change appearance * * @method handlePlay */ PlayToggle.prototype.handlePlay = function handlePlay() { this.removeClass('vjs-paused'); this.addClass('vjs-playing'); this.controlText('Pause'); // change the button text to "Pause" }; /** * Add the vjs-paused class to the element so it can change appearance * * @method handlePause */ PlayToggle.prototype.handlePause = function handlePause() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.controlText('Play'); // change the button text to "Play" }; return PlayToggle; })(_Button3['default']); PlayToggle.prototype.controlText_ = 'Play'; _Component2['default'].registerComponent('PlayToggle', PlayToggle); exports['default'] = PlayToggle; module.exports = exports['default']; },{"../button.js":51,"../component.js":52}],58:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file playback-rate-menu-button.js */ var _MenuButton2 = _dereq_('../../menu/menu-button.js'); var _MenuButton3 = _interopRequireWildcard(_MenuButton2); var _Menu = _dereq_('../../menu/menu.js'); var _Menu2 = _interopRequireWildcard(_Menu); var _PlaybackRateMenuItem = _dereq_('./playback-rate-menu-item.js'); var _PlaybackRateMenuItem2 = _interopRequireWildcard(_PlaybackRateMenuItem); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_import); /** * The component for controlling the playback rate * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class PlaybackRateMenuButton */ var PlaybackRateMenuButton = (function (_MenuButton) { function PlaybackRateMenuButton(player, options) { _classCallCheck(this, PlaybackRateMenuButton); _MenuButton.call(this, player, options); this.updateVisibility(); this.updateLabel(); this.on(player, 'loadstart', this.updateVisibility); this.on(player, 'ratechange', this.updateLabel); } _inherits(PlaybackRateMenuButton, _MenuButton); /** * Create the component's DOM element * * @return {Element} * @method createEl */ PlaybackRateMenuButton.prototype.createEl = function createEl() { var el = _MenuButton.prototype.createEl.call(this); this.labelEl_ = Dom.createEl('div', { className: 'vjs-playback-rate-value', innerHTML: 1 }); el.appendChild(this.labelEl_); return el; }; /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ PlaybackRateMenuButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-playback-rate ' + _MenuButton.prototype.buildCSSClass.call(this); }; /** * Create the playback rate menu * * @return {Menu} Menu object populated with items * @method createMenu */ PlaybackRateMenuButton.prototype.createMenu = function createMenu() { var menu = new _Menu2['default'](this.player()); var rates = this.playbackRates(); if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addChild(new _PlaybackRateMenuItem2['default'](this.player(), { rate: rates[i] + 'x' })); } } return menu; }; /** * Updates ARIA accessibility attributes * * @method updateARIAAttributes */ PlaybackRateMenuButton.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current playback rate this.el().setAttribute('aria-valuenow', this.player().playbackRate()); }; /** * Handle menu item click * * @method handleClick */ PlaybackRateMenuButton.prototype.handleClick = function handleClick() { // select next rate option var currentRate = this.player().playbackRate(); var rates = this.playbackRates(); // this will select first one if the last one currently selected var newRate = rates[0]; for (var i = 0; i < rates.length; i++) { if (rates[i] > currentRate) { newRate = rates[i]; break; } } this.player().playbackRate(newRate); }; /** * Get possible playback rates * * @return {Array} Possible playback rates * @method playbackRates */ PlaybackRateMenuButton.prototype.playbackRates = function playbackRates() { return this.options_.playbackRates || this.options_.playerOptions && this.options_.playerOptions.playbackRates; }; /** * Get supported playback rates * * @return {Array} Supported playback rates * @method playbackRateSupported */ PlaybackRateMenuButton.prototype.playbackRateSupported = function playbackRateSupported() { return this.player().tech && this.player().tech.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0; }; /** * Hide playback rate controls when they're no playback rate options to select * * @method updateVisibility */ PlaybackRateMenuButton.prototype.updateVisibility = function updateVisibility() { if (this.playbackRateSupported()) { this.removeClass('vjs-hidden'); } else { this.addClass('vjs-hidden'); } }; /** * Update button label when rate changed * * @method updateLabel */ PlaybackRateMenuButton.prototype.updateLabel = function updateLabel() { if (this.playbackRateSupported()) { this.labelEl_.innerHTML = this.player().playbackRate() + 'x'; } }; return PlaybackRateMenuButton; })(_MenuButton3['default']); PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate'; _Component2['default'].registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton); exports['default'] = PlaybackRateMenuButton; module.exports = exports['default']; },{"../../component.js":52,"../../menu/menu-button.js":89,"../../menu/menu.js":91,"../../utils/dom.js":111,"./playback-rate-menu-item.js":59}],59:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file playback-rate-menu-item.js */ var _MenuItem2 = _dereq_('../../menu/menu-item.js'); var _MenuItem3 = _interopRequireWildcard(_MenuItem2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * The specific menu item type for selecting a playback rate * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class PlaybackRateMenuItem */ var PlaybackRateMenuItem = (function (_MenuItem) { function PlaybackRateMenuItem(player, options) { _classCallCheck(this, PlaybackRateMenuItem); var label = options.rate; var rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init. options.label = label; options.selected = rate === 1; _MenuItem.call(this, player, options); this.label = label; this.rate = rate; this.on(player, 'ratechange', this.update); } _inherits(PlaybackRateMenuItem, _MenuItem); /** * Handle click on menu item * * @method handleClick */ PlaybackRateMenuItem.prototype.handleClick = function handleClick() { _MenuItem.prototype.handleClick.call(this); this.player().playbackRate(this.rate); }; /** * Update playback rate with selected rate * * @method update */ PlaybackRateMenuItem.prototype.update = function update() { this.selected(this.player().playbackRate() === this.rate); }; return PlaybackRateMenuItem; })(_MenuItem3['default']); PlaybackRateMenuItem.prototype.contentElType = 'button'; _Component2['default'].registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem); exports['default'] = PlaybackRateMenuItem; module.exports = exports['default']; },{"../../component.js":52,"../../menu/menu-item.js":90}],60:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file load-progress-bar.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_import); /** * Shows load progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class LoadProgressBar */ var LoadProgressBar = (function (_Component) { function LoadProgressBar(player, options) { _classCallCheck(this, LoadProgressBar); _Component.call(this, player, options); this.on(player, 'progress', this.update); } _inherits(LoadProgressBar, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ LoadProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>' }); }; /** * Update progress bar * * @method update */ LoadProgressBar.prototype.update = function update() { var buffered = this.player_.buffered(); var duration = this.player_.duration(); var bufferedEnd = this.player_.bufferedEnd(); var children = this.el_.children; // get the percent width of a time compared to the total end var percentify = function percentify(time, end) { var percent = time / end || 0; // no NaN return (percent >= 1 ? 1 : percent) * 100 + '%'; }; // update the width of the progress bar this.el_.style.width = percentify(bufferedEnd, duration); // add child elements to represent the individual buffered time ranges for (var i = 0; i < buffered.length; i++) { var start = buffered.start(i); var end = buffered.end(i); var part = children[i]; if (!part) { part = this.el_.appendChild(Dom.createEl()); } // set the percent based on the width of the progress bar (bufferedEnd) part.style.left = percentify(start, bufferedEnd); part.style.width = percentify(end - start, bufferedEnd); } // remove unused buffered range elements for (var i = children.length; i > buffered.length; i--) { this.el_.removeChild(children[i - 1]); } }; return LoadProgressBar; })(_Component3['default']); _Component3['default'].registerComponent('LoadProgressBar', LoadProgressBar); exports['default'] = LoadProgressBar; module.exports = exports['default']; },{"../../component.js":52,"../../utils/dom.js":111}],61:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file play-progress-bar.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _formatTime = _dereq_('../../utils/format-time.js'); var _formatTime2 = _interopRequireWildcard(_formatTime); /** * Shows play progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class PlayProgressBar */ var PlayProgressBar = (function (_Component) { function PlayProgressBar(player, options) { _classCallCheck(this, PlayProgressBar); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateDataAttr); player.ready(Fn.bind(this, this.updateDataAttr)); } _inherits(PlayProgressBar, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ PlayProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>' }); }; PlayProgressBar.prototype.updateDataAttr = function updateDataAttr() { var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('data-current-time', _formatTime2['default'](time, this.player_.duration())); }; return PlayProgressBar; })(_Component3['default']); _Component3['default'].registerComponent('PlayProgressBar', PlayProgressBar); exports['default'] = PlayProgressBar; module.exports = exports['default']; },{"../../component.js":52,"../../utils/fn.js":113,"../../utils/format-time.js":114}],62:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file progress-control.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _SeekBar = _dereq_('./seek-bar.js'); var _SeekBar2 = _interopRequireWildcard(_SeekBar); /** * The Progress Control component contains the seek bar, load progress, * and play progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class ProgressControl */ var ProgressControl = (function (_Component) { function ProgressControl() { _classCallCheck(this, ProgressControl); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(ProgressControl, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ ProgressControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); }; return ProgressControl; })(_Component3['default']); ProgressControl.prototype.options_ = { children: { seekBar: {} } }; _Component3['default'].registerComponent('ProgressControl', ProgressControl); exports['default'] = ProgressControl; module.exports = exports['default']; },{"../../component.js":52,"./seek-bar.js":63}],63:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file seek-bar.js */ var _Slider2 = _dereq_('../../slider/slider.js'); var _Slider3 = _interopRequireWildcard(_Slider2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _LoadProgressBar = _dereq_('./load-progress-bar.js'); var _LoadProgressBar2 = _interopRequireWildcard(_LoadProgressBar); var _PlayProgressBar = _dereq_('./play-progress-bar.js'); var _PlayProgressBar2 = _interopRequireWildcard(_PlayProgressBar); var _import = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _formatTime = _dereq_('../../utils/format-time.js'); var _formatTime2 = _interopRequireWildcard(_formatTime); /** * Seek Bar and holder for the progress bars * * @param {Player|Object} player * @param {Object=} options * @extends Slider * @class SeekBar */ var SeekBar = (function (_Slider) { function SeekBar(player, options) { _classCallCheck(this, SeekBar); _Slider.call(this, player, options); this.on(player, 'timeupdate', this.updateARIAAttributes); player.ready(Fn.bind(this, this.updateARIAAttributes)); } _inherits(SeekBar, _Slider); /** * Create the component's DOM element * * @return {Element} * @method createEl */ SeekBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder', 'aria-label': 'video progress bar' }); }; /** * Update ARIA accessibility attributes * * @method updateARIAAttributes */ SeekBar.prototype.updateARIAAttributes = function updateARIAAttributes() { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('aria-valuenow', (this.getPercent() * 100).toFixed(2)); // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuetext', _formatTime2['default'](time, this.player_.duration())); // human readable value of progress bar (time complete) }; /** * Get percentage of video played * * @return {Number} Percentage played * @method getPercent */ SeekBar.prototype.getPercent = function getPercent() { var percent = this.player_.currentTime() / this.player_.duration(); return percent >= 1 ? 1 : percent; }; /** * Handle mouse down on seek bar * * @method handleMouseDown */ SeekBar.prototype.handleMouseDown = function handleMouseDown(event) { _Slider.prototype.handleMouseDown.call(this, event); this.player_.scrubbing(true); this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); }; /** * Handle mouse move on seek bar * * @method handleMouseMove */ SeekBar.prototype.handleMouseMove = function handleMouseMove(event) { var newTime = this.calculateDistance(event) * this.player_.duration(); // Don't let video end while scrubbing. if (newTime === this.player_.duration()) { newTime = newTime - 0.1; } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); }; /** * Handle mouse up on seek bar * * @method handleMouseUp */ SeekBar.prototype.handleMouseUp = function handleMouseUp(event) { _Slider.prototype.handleMouseUp.call(this, event); this.player_.scrubbing(false); if (this.videoWasPlaying) { this.player_.play(); } }; /** * Move more quickly fast forward for keyboard-only users * * @method stepForward */ SeekBar.prototype.stepForward = function stepForward() { this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users }; /** * Move more quickly rewind for keyboard-only users * * @method stepBack */ SeekBar.prototype.stepBack = function stepBack() { this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users }; return SeekBar; })(_Slider3['default']); SeekBar.prototype.options_ = { children: { loadProgressBar: {}, playProgressBar: {} }, barName: 'playProgressBar' }; SeekBar.prototype.playerEvent = 'timeupdate'; _Component2['default'].registerComponent('SeekBar', SeekBar); exports['default'] = SeekBar; module.exports = exports['default']; },{"../../component.js":52,"../../slider/slider.js":96,"../../utils/fn.js":113,"../../utils/format-time.js":114,"./load-progress-bar.js":60,"./play-progress-bar.js":61}],64:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file custom-control-spacer.js */ var _Spacer2 = _dereq_('./spacer.js'); var _Spacer3 = _interopRequireWildcard(_Spacer2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * Spacer specifically meant to be used as an insertion point for new plugins, etc. * * @extends Spacer * @class CustomControlSpacer */ var CustomControlSpacer = (function (_Spacer) { function CustomControlSpacer() { _classCallCheck(this, CustomControlSpacer); if (_Spacer != null) { _Spacer.apply(this, arguments); } } _inherits(CustomControlSpacer, _Spacer); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ CustomControlSpacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-custom-control-spacer ' + _Spacer.prototype.buildCSSClass.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ CustomControlSpacer.prototype.createEl = function createEl() { return _Spacer.prototype.createEl.call(this, { className: this.buildCSSClass() }); }; return CustomControlSpacer; })(_Spacer3['default']); _Component2['default'].registerComponent('CustomControlSpacer', CustomControlSpacer); exports['default'] = CustomControlSpacer; module.exports = exports['default']; },{"../../component.js":52,"./spacer.js":65}],65:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file spacer.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); /** * Just an empty spacer element that can be used as an append point for plugins, etc. * Also can be used to create space between elements when necessary. * * @extends Component * @class Spacer */ var Spacer = (function (_Component) { function Spacer() { _classCallCheck(this, Spacer); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(Spacer, _Component); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ Spacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-spacer ' + _Component.prototype.buildCSSClass.call(this); }; /** * Create the component's DOM element * * @param {Object} props An object of properties * @return {Element} * @method createEl */ Spacer.prototype.createEl = function createEl(props) { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; return Spacer; })(_Component3['default']); _Component3['default'].registerComponent('Spacer', Spacer); exports['default'] = Spacer; module.exports = exports['default']; },{"../../component.js":52}],66:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file caption-settings-menu-item.js */ var _TextTrackMenuItem2 = _dereq_('./text-track-menu-item.js'); var _TextTrackMenuItem3 = _interopRequireWildcard(_TextTrackMenuItem2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * The menu item for caption track settings menu * * @param {Player|Object} player * @param {Object=} options * @extends TextTrackMenuItem * @class CaptionSettingsMenuItem */ var CaptionSettingsMenuItem = (function (_TextTrackMenuItem) { function CaptionSettingsMenuItem(player, options) { _classCallCheck(this, CaptionSettingsMenuItem); options.track = { kind: options.kind, player: player, label: options.kind + ' settings', 'default': false, mode: 'disabled' }; _TextTrackMenuItem.call(this, player, options); this.addClass('vjs-texttrack-settings'); } _inherits(CaptionSettingsMenuItem, _TextTrackMenuItem); /** * Handle click on menu item * * @method handleClick */ CaptionSettingsMenuItem.prototype.handleClick = function handleClick() { this.player().getChild('textTrackSettings').show(); }; return CaptionSettingsMenuItem; })(_TextTrackMenuItem3['default']); _Component2['default'].registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem); exports['default'] = CaptionSettingsMenuItem; module.exports = exports['default']; },{"../../component.js":52,"./text-track-menu-item.js":73}],67:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file captions-button.js */ var _TextTrackButton2 = _dereq_('./text-track-button.js'); var _TextTrackButton3 = _interopRequireWildcard(_TextTrackButton2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _CaptionSettingsMenuItem = _dereq_('./caption-settings-menu-item.js'); var _CaptionSettingsMenuItem2 = _interopRequireWildcard(_CaptionSettingsMenuItem); /** * The button component for toggling and selecting captions * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class CaptionsButton */ var CaptionsButton = (function (_TextTrackButton) { function CaptionsButton(player, options, ready) { _classCallCheck(this, CaptionsButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Captions Menu'); } _inherits(CaptionsButton, _TextTrackButton); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ CaptionsButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-captions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Update caption menu items * * @method update */ CaptionsButton.prototype.update = function update() { var threshold = 2; _TextTrackButton.prototype.update.call(this); // if native, then threshold is 1 because no settings button if (this.player().tech && this.player().tech.featuresNativeTextTracks) { threshold = 1; } if (this.items && this.items.length > threshold) { this.show(); } else { this.hide(); } }; /** * Create caption menu items * * @return {Array} Array of menu items * @method createItems */ CaptionsButton.prototype.createItems = function createItems() { var items = []; if (!(this.player().tech && this.player().tech.featuresNativeTextTracks)) { items.push(new _CaptionSettingsMenuItem2['default'](this.player_, { kind: this.kind_ })); } return _TextTrackButton.prototype.createItems.call(this, items); }; return CaptionsButton; })(_TextTrackButton3['default']); CaptionsButton.prototype.kind_ = 'captions'; CaptionsButton.prototype.controlText_ = 'Captions'; _Component2['default'].registerComponent('CaptionsButton', CaptionsButton); exports['default'] = CaptionsButton; module.exports = exports['default']; },{"../../component.js":52,"./caption-settings-menu-item.js":66,"./text-track-button.js":72}],68:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file chapters-button.js */ var _TextTrackButton2 = _dereq_('./text-track-button.js'); var _TextTrackButton3 = _interopRequireWildcard(_TextTrackButton2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _TextTrackMenuItem = _dereq_('./text-track-menu-item.js'); var _TextTrackMenuItem2 = _interopRequireWildcard(_TextTrackMenuItem); var _ChaptersTrackMenuItem = _dereq_('./chapters-track-menu-item.js'); var _ChaptersTrackMenuItem2 = _interopRequireWildcard(_ChaptersTrackMenuItem); var _Menu = _dereq_('../../menu/menu.js'); var _Menu2 = _interopRequireWildcard(_Menu); var _import = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import2); var _toTitleCase = _dereq_('../../utils/to-title-case.js'); var _toTitleCase2 = _interopRequireWildcard(_toTitleCase); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); /** * The button component for toggling and selecting chapters * Chapters act much differently than other text tracks * Cues are navigation vs. other tracks of alternative languages * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class ChaptersButton */ var ChaptersButton = (function (_TextTrackButton) { function ChaptersButton(player, options, ready) { _classCallCheck(this, ChaptersButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Chapters Menu'); } _inherits(ChaptersButton, _TextTrackButton); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ ChaptersButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-chapters-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Create a menu item for each text track * * @return {Array} Array of menu items * @method createItems */ ChaptersButton.prototype.createItems = function createItems() { var items = []; var tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track.kind === this.kind_) { items.push(new _TextTrackMenuItem2['default'](this.player_, { track: track })); } } return items; }; /** * Create menu from chapter buttons * * @return {Menu} Menu of chapter buttons * @method createMenu */ ChaptersButton.prototype.createMenu = function createMenu() { var tracks = this.player_.textTracks() || []; var chaptersTrack = undefined; var items = this.items = []; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track.kind === this.kind_) { if (!track.cues) { track.mode = 'hidden'; /* jshint loopfunc:true */ // TODO see if we can figure out a better way of doing this https://github.com/videojs/video.js/issues/1864 _window2['default'].setTimeout(Fn.bind(this, function () { this.createMenu(); }), 100); /* jshint loopfunc:false */ } else { chaptersTrack = track; break; } } } var menu = this.menu; if (menu === undefined) { menu = new _Menu2['default'](this.player_); menu.contentEl().appendChild(Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: _toTitleCase2['default'](this.kind_), tabIndex: -1 })); } if (chaptersTrack) { var cues = chaptersTrack.cues, cue = undefined; for (var i = 0, l = cues.length; i < l; i++) { cue = cues[i]; var mi = new _ChaptersTrackMenuItem2['default'](this.player_, { track: chaptersTrack, cue: cue }); items.push(mi); menu.addChild(mi); } this.addChild(menu); } if (this.items.length > 0) { this.show(); } return menu; }; return ChaptersButton; })(_TextTrackButton3['default']); ChaptersButton.prototype.kind_ = 'chapters'; ChaptersButton.prototype.controlText_ = 'Chapters'; _Component2['default'].registerComponent('ChaptersButton', ChaptersButton); exports['default'] = ChaptersButton; module.exports = exports['default']; },{"../../component.js":52,"../../menu/menu.js":91,"../../utils/dom.js":111,"../../utils/fn.js":113,"../../utils/to-title-case.js":119,"./chapters-track-menu-item.js":69,"./text-track-button.js":72,"./text-track-menu-item.js":73,"global/window":2}],69:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file chapters-track-menu-item.js */ var _MenuItem2 = _dereq_('../../menu/menu-item.js'); var _MenuItem3 = _interopRequireWildcard(_MenuItem2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import); /** * The chapter track menu item * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class ChaptersTrackMenuItem */ var ChaptersTrackMenuItem = (function (_MenuItem) { function ChaptersTrackMenuItem(player, options) { _classCallCheck(this, ChaptersTrackMenuItem); var track = options.track; var cue = options.cue; var currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options.label = cue.text; options.selected = cue.startTime <= currentTime && currentTime < cue.endTime; _MenuItem.call(this, player, options); this.track = track; this.cue = cue; track.addEventListener('cuechange', Fn.bind(this, this.update)); } _inherits(ChaptersTrackMenuItem, _MenuItem); /** * Handle click on menu item * * @method handleClick */ ChaptersTrackMenuItem.prototype.handleClick = function handleClick() { _MenuItem.prototype.handleClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); }; /** * Update chapter menu item * * @method update */ ChaptersTrackMenuItem.prototype.update = function update() { var cue = this.cue; var currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue.startTime <= currentTime && currentTime < cue.endTime); }; return ChaptersTrackMenuItem; })(_MenuItem3['default']); _Component2['default'].registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem); exports['default'] = ChaptersTrackMenuItem; module.exports = exports['default']; },{"../../component.js":52,"../../menu/menu-item.js":90,"../../utils/fn.js":113}],70:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file off-text-track-menu-item.js */ var _TextTrackMenuItem2 = _dereq_('./text-track-menu-item.js'); var _TextTrackMenuItem3 = _interopRequireWildcard(_TextTrackMenuItem2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * A special menu item for turning of a specific type of text track * * @param {Player|Object} player * @param {Object=} options * @extends TextTrackMenuItem * @class OffTextTrackMenuItem */ var OffTextTrackMenuItem = (function (_TextTrackMenuItem) { function OffTextTrackMenuItem(player, options) { _classCallCheck(this, OffTextTrackMenuItem); // Create pseudo track info // Requires options['kind'] options.track = { kind: options.kind, player: player, label: options.kind + ' off', 'default': false, mode: 'disabled' }; _TextTrackMenuItem.call(this, player, options); this.selected(true); } _inherits(OffTextTrackMenuItem, _TextTrackMenuItem); /** * Handle text track change * * @param {Object} event Event object * @method handleTracksChange */ OffTextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { var tracks = this.player().textTracks(); var selected = true; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track.kind === this.track.kind && track.mode === 'showing') { selected = false; break; } } this.selected(selected); }; return OffTextTrackMenuItem; })(_TextTrackMenuItem3['default']); _Component2['default'].registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem); exports['default'] = OffTextTrackMenuItem; module.exports = exports['default']; },{"../../component.js":52,"./text-track-menu-item.js":73}],71:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file subtitles-button.js */ var _TextTrackButton2 = _dereq_('./text-track-button.js'); var _TextTrackButton3 = _interopRequireWildcard(_TextTrackButton2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * The button component for toggling and selecting subtitles * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class SubtitlesButton */ var SubtitlesButton = (function (_TextTrackButton) { function SubtitlesButton(player, options, ready) { _classCallCheck(this, SubtitlesButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Subtitles Menu'); } _inherits(SubtitlesButton, _TextTrackButton); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ SubtitlesButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-subtitles-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; return SubtitlesButton; })(_TextTrackButton3['default']); SubtitlesButton.prototype.kind_ = 'subtitles'; SubtitlesButton.prototype.controlText_ = 'Subtitles'; _Component2['default'].registerComponent('SubtitlesButton', SubtitlesButton); exports['default'] = SubtitlesButton; module.exports = exports['default']; },{"../../component.js":52,"./text-track-button.js":72}],72:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file text-track-button.js */ var _MenuButton2 = _dereq_('../../menu/menu-button.js'); var _MenuButton3 = _interopRequireWildcard(_MenuButton2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _TextTrackMenuItem = _dereq_('./text-track-menu-item.js'); var _TextTrackMenuItem2 = _interopRequireWildcard(_TextTrackMenuItem); var _OffTextTrackMenuItem = _dereq_('./off-text-track-menu-item.js'); var _OffTextTrackMenuItem2 = _interopRequireWildcard(_OffTextTrackMenuItem); /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class TextTrackButton */ var TextTrackButton = (function (_MenuButton) { function TextTrackButton(player, options) { _classCallCheck(this, TextTrackButton); _MenuButton.call(this, player, options); var tracks = this.player_.textTracks(); if (this.items.length <= 1) { this.hide(); } if (!tracks) { return; } var updateHandler = Fn.bind(this, this.update); tracks.addEventListener('removetrack', updateHandler); tracks.addEventListener('addtrack', updateHandler); this.player_.on('dispose', function () { tracks.removeEventListener('removetrack', updateHandler); tracks.removeEventListener('addtrack', updateHandler); }); } _inherits(TextTrackButton, _MenuButton); // Create a menu item for each text track TextTrackButton.prototype.createItems = function createItems() { var items = arguments[0] === undefined ? [] : arguments[0]; // Add an OFF menu item to turn all tracks off items.push(new _OffTextTrackMenuItem2['default'](this.player_, { kind: this.kind_ })); var tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // only add tracks that are of the appropriate kind and have a label if (track.kind === this.kind_) { items.push(new _TextTrackMenuItem2['default'](this.player_, { track: track })); } } return items; }; return TextTrackButton; })(_MenuButton3['default']); _Component2['default'].registerComponent('TextTrackButton', TextTrackButton); exports['default'] = TextTrackButton; module.exports = exports['default']; },{"../../component.js":52,"../../menu/menu-button.js":89,"../../utils/fn.js":113,"./off-text-track-menu-item.js":70,"./text-track-menu-item.js":73}],73:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file text-track-menu-item.js */ var _MenuItem2 = _dereq_('../../menu/menu-item.js'); var _MenuItem3 = _interopRequireWildcard(_MenuItem2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); /** * The specific menu item type for selecting a language within a text track kind * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class TextTrackMenuItem */ var TextTrackMenuItem = (function (_MenuItem) { function TextTrackMenuItem(player, options) { var _this = this; _classCallCheck(this, TextTrackMenuItem); var track = options.track; var tracks = player.textTracks(); // Modify options for parent MenuItem class's init. options.label = track.label || track.language || 'Unknown'; options.selected = track['default'] || track.mode === 'showing'; _MenuItem.call(this, player, options); this.track = track; if (tracks) { (function () { var changeHandler = Fn.bind(_this, _this.handleTracksChange); tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); })(); } // iOS7 doesn't dispatch change events to TextTrackLists when an // associated track's mode changes. Without something like // Object.observe() (also not present on iOS7), it's not // possible to detect changes to the mode attribute and polyfill // the change event. As a poor substitute, we manually dispatch // change events whenever the controls modify the mode. if (tracks && tracks.onchange === undefined) { (function () { var event = undefined; _this.on(['tap', 'click'], function () { if (typeof _window2['default'].Event !== 'object') { // Android 2.3 throws an Illegal Constructor error for window.Event try { event = new _window2['default'].Event('change'); } catch (err) {} } if (!event) { event = _document2['default'].createEvent('Event'); event.initEvent('change', true, true); } tracks.dispatchEvent(event); }); })(); } } _inherits(TextTrackMenuItem, _MenuItem); /** * Handle click on text track * * @method handleClick */ TextTrackMenuItem.prototype.handleClick = function handleClick(event) { var kind = this.track.kind; var tracks = this.player_.textTracks(); _MenuItem.prototype.handleClick.call(this, event); if (!tracks) { return; }for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track.kind !== kind) { continue; } if (track === this.track) { track.mode = 'showing'; } else { track.mode = 'disabled'; } } }; /** * Handle text track change * * @method handleTracksChange */ TextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { this.selected(this.track.mode === 'showing'); }; return TextTrackMenuItem; })(_MenuItem3['default']); _Component2['default'].registerComponent('TextTrackMenuItem', TextTrackMenuItem); exports['default'] = TextTrackMenuItem; module.exports = exports['default']; },{"../../component.js":52,"../../menu/menu-item.js":90,"../../utils/fn.js":113,"global/document":1,"global/window":2}],74:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file current-time-display.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _formatTime = _dereq_('../../utils/format-time.js'); var _formatTime2 = _interopRequireWildcard(_formatTime); /** * Displays the current time * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class CurrentTimeDisplay */ var CurrentTimeDisplay = (function (_Component) { function CurrentTimeDisplay(player, options) { _classCallCheck(this, CurrentTimeDisplay); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } _inherits(CurrentTimeDisplay, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ CurrentTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-current-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-current-time-display', innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00', // label the current time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; /** * Update current time display * * @method updateContent */ CurrentTimeDisplay.prototype.updateContent = function updateContent() { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing ? this.player_.getCache().currentTime : this.player_.currentTime(); var localizedText = this.localize('Current Time'); var formattedTime = _formatTime2['default'](time, this.player_.duration()); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; }; return CurrentTimeDisplay; })(_Component3['default']); _Component3['default'].registerComponent('CurrentTimeDisplay', CurrentTimeDisplay); exports['default'] = CurrentTimeDisplay; module.exports = exports['default']; },{"../../component.js":52,"../../utils/dom.js":111,"../../utils/format-time.js":114}],75:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file duration-display.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _formatTime = _dereq_('../../utils/format-time.js'); var _formatTime2 = _interopRequireWildcard(_formatTime); /** * Displays the duration * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class DurationDisplay */ var DurationDisplay = (function (_Component) { function DurationDisplay(player, options) { _classCallCheck(this, DurationDisplay); _Component.call(this, player, options); // this might need to be changed to 'durationchange' instead of 'timeupdate' eventually, // however the durationchange event fires before this.player_.duration() is set, // so the value cannot be written out using this method. // Once the order of durationchange and this.player_.duration() being set is figured out, // this can be updated. this.on(player, 'timeupdate', this.updateContent); this.on(player, 'loadedmetadata', this.updateContent); } _inherits(DurationDisplay, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ DurationDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-duration vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-duration-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> 0:00', // label the duration time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; /** * Update duration time display * * @method updateContent */ DurationDisplay.prototype.updateContent = function updateContent() { var duration = this.player_.duration(); if (duration) { var localizedText = this.localize('Duration Time'); var formattedTime = _formatTime2['default'](duration); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; // label the duration time for screen reader users } }; return DurationDisplay; })(_Component3['default']); _Component3['default'].registerComponent('DurationDisplay', DurationDisplay); exports['default'] = DurationDisplay; module.exports = exports['default']; },{"../../component.js":52,"../../utils/dom.js":111,"../../utils/format-time.js":114}],76:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file remaining-time-display.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _formatTime = _dereq_('../../utils/format-time.js'); var _formatTime2 = _interopRequireWildcard(_formatTime); /** * Displays the time left in the video * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class RemainingTimeDisplay */ var RemainingTimeDisplay = (function (_Component) { function RemainingTimeDisplay(player, options) { _classCallCheck(this, RemainingTimeDisplay); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } _inherits(RemainingTimeDisplay, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ RemainingTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-remaining-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-remaining-time-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> -0:00', // label the remaining time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; /** * Update remaining time display * * @method updateContent */ RemainingTimeDisplay.prototype.updateContent = function updateContent() { if (this.player_.duration()) { var localizedText = this.localize('Remaining Time'); var formattedTime = _formatTime2['default'](this.player_.remainingTime()); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> -' + formattedTime; } // Allows for smooth scrubbing, when player can't keep up. // var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); // this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration()); }; return RemainingTimeDisplay; })(_Component3['default']); _Component3['default'].registerComponent('RemainingTimeDisplay', RemainingTimeDisplay); exports['default'] = RemainingTimeDisplay; module.exports = exports['default']; },{"../../component.js":52,"../../utils/dom.js":111,"../../utils/format-time.js":114}],77:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file time-divider.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); /** * The separator between the current time and duration. * Can be hidden if it's not needed in the design. * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class TimeDivider */ var TimeDivider = (function (_Component) { function TimeDivider() { _classCallCheck(this, TimeDivider); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(TimeDivider, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ TimeDivider.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-control vjs-time-divider', innerHTML: '<div><span>/</span></div>' }); }; return TimeDivider; })(_Component3['default']); _Component3['default'].registerComponent('TimeDivider', TimeDivider); exports['default'] = TimeDivider; module.exports = exports['default']; },{"../../component.js":52}],78:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file volume-bar.js */ var _Slider2 = _dereq_('../../slider/slider.js'); var _Slider3 = _interopRequireWildcard(_Slider2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import); // Required children var _VolumeLevel = _dereq_('./volume-level.js'); var _VolumeLevel2 = _interopRequireWildcard(_VolumeLevel); /** * The bar that contains the volume level and can be clicked on to adjust the level * * @param {Player|Object} player * @param {Object=} options * @extends Slider * @class VolumeBar */ var VolumeBar = (function (_Slider) { function VolumeBar(player, options) { _classCallCheck(this, VolumeBar); _Slider.call(this, player, options); this.on(player, 'volumechange', this.updateARIAAttributes); player.ready(Fn.bind(this, this.updateARIAAttributes)); } _inherits(VolumeBar, _Slider); /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar', 'aria-label': 'volume level' }); }; /** * Handle mouse move on volume bar * * @method handleMouseMove */ VolumeBar.prototype.handleMouseMove = function handleMouseMove(event) { if (this.player_.muted()) { this.player_.muted(false); } this.player_.volume(this.calculateDistance(event)); }; /** * Get percent of volume level * * @retun {Number} Volume level percent * @method getPercent */ VolumeBar.prototype.getPercent = function getPercent() { if (this.player_.muted()) { return 0; } else { return this.player_.volume(); } }; /** * Increase volume level for keyboard users * * @method stepForward */ VolumeBar.prototype.stepForward = function stepForward() { this.player_.volume(this.player_.volume() + 0.1); }; /** * Decrease volume level for keyboard users * * @method stepBack */ VolumeBar.prototype.stepBack = function stepBack() { this.player_.volume(this.player_.volume() - 0.1); }; /** * Update ARIA accessibility attributes * * @method updateARIAAttributes */ VolumeBar.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current value of volume bar as a percentage var volume = (this.player_.volume() * 100).toFixed(2); this.el_.setAttribute('aria-valuenow', volume); this.el_.setAttribute('aria-valuetext', volume + '%'); }; return VolumeBar; })(_Slider3['default']); VolumeBar.prototype.options_ = { children: { volumeLevel: {} }, barName: 'volumeLevel' }; VolumeBar.prototype.playerEvent = 'volumechange'; _Component2['default'].registerComponent('VolumeBar', VolumeBar); exports['default'] = VolumeBar; module.exports = exports['default']; },{"../../component.js":52,"../../slider/slider.js":96,"../../utils/fn.js":113,"./volume-level.js":80}],79:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file volume-control.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); // Required children var _VolumeBar = _dereq_('./volume-bar.js'); var _VolumeBar2 = _interopRequireWildcard(_VolumeBar); /** * The component for controlling the volume level * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class VolumeControl */ var VolumeControl = (function (_Component) { function VolumeControl(player, options) { _classCallCheck(this, VolumeControl); _Component.call(this, player, options); // hide volume controls when they're not supported by the current tech if (player.tech && player.tech.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { if (player.tech.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } _inherits(VolumeControl, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-control vjs-control' }); }; return VolumeControl; })(_Component3['default']); VolumeControl.prototype.options_ = { children: { volumeBar: {} } }; _Component3['default'].registerComponent('VolumeControl', VolumeControl); exports['default'] = VolumeControl; module.exports = exports['default']; },{"../../component.js":52,"./volume-bar.js":78}],80:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file volume-level.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); /** * Shows volume level * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class VolumeLevel */ var VolumeLevel = (function (_Component) { function VolumeLevel() { _classCallCheck(this, VolumeLevel); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(VolumeLevel, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeLevel.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; return VolumeLevel; })(_Component3['default']); _Component3['default'].registerComponent('VolumeLevel', VolumeLevel); exports['default'] = VolumeLevel; module.exports = exports['default']; },{"../../component.js":52}],81:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file volume-menu-button.js */ var _Button = _dereq_('../button.js'); var _Button2 = _interopRequireWildcard(_Button); var _Component = _dereq_('../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _Menu = _dereq_('../menu/menu.js'); var _Menu2 = _interopRequireWildcard(_Menu); var _MenuButton2 = _dereq_('../menu/menu-button.js'); var _MenuButton3 = _interopRequireWildcard(_MenuButton2); var _MuteToggle = _dereq_('./mute-toggle.js'); var _MuteToggle2 = _interopRequireWildcard(_MuteToggle); var _VolumeBar = _dereq_('./volume-control/volume-bar.js'); var _VolumeBar2 = _interopRequireWildcard(_VolumeBar); /** * Button for volume menu * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class VolumeMenuButton */ var VolumeMenuButton = (function (_MenuButton) { function VolumeMenuButton(player) { var options = arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, VolumeMenuButton); // If the vertical option isn't passed at all, default to true. if (options.vertical === undefined) { // If an inline volumeMenuButton is used, we should default to using a horizontal // slider for obvious reasons. if (options.inline) { options.vertical = false; } else { options.vertical = true; } } // The vertical option needs to be set on the volumeBar as well, since that will // need to be passed along to the VolumeBar constructor options.volumeBar = options.volumeBar || {}; options.volumeBar.vertical = !!options.vertical; _MenuButton.call(this, player, options); // Same listeners as MuteToggle this.on(player, 'volumechange', this.volumeUpdate); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { if (player.tech.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); this.addClass('vjs-menu-button'); } _inherits(VolumeMenuButton, _MenuButton); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ VolumeMenuButton.prototype.buildCSSClass = function buildCSSClass() { var orientationClass = ''; if (!!this.options_.vertical) { orientationClass = 'vjs-volume-menu-button-vertical'; } else { orientationClass = 'vjs-volume-menu-button-horizontal'; } return 'vjs-volume-menu-button ' + _MenuButton.prototype.buildCSSClass.call(this) + ' ' + orientationClass; }; /** * Allow sub components to stack CSS class names * * @return {Menu} The volume menu button * @method createMenu */ VolumeMenuButton.prototype.createMenu = function createMenu() { var menu = new _Menu2['default'](this.player_, { contentElType: 'div' }); var vc = new _VolumeBar2['default'](this.player_, this.options_.volumeBar); vc.on('focus', function () { menu.lockShowing(); }); vc.on('blur', function () { menu.unlockShowing(); }); menu.addChild(vc); return menu; }; /** * Handle click on volume menu and calls super * * @method handleClick */ VolumeMenuButton.prototype.handleClick = function handleClick() { _MuteToggle2['default'].prototype.handleClick.call(this); _MenuButton.prototype.handleClick.call(this); }; return VolumeMenuButton; })(_MenuButton3['default']); VolumeMenuButton.prototype.volumeUpdate = _MuteToggle2['default'].prototype.update; VolumeMenuButton.prototype.controlText_ = 'Mute'; _Component2['default'].registerComponent('VolumeMenuButton', VolumeMenuButton); exports['default'] = VolumeMenuButton; module.exports = exports['default']; },{"../button.js":51,"../component.js":52,"../menu/menu-button.js":89,"../menu/menu.js":91,"./mute-toggle.js":56,"./volume-control/volume-bar.js":78}],82:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file error-display.js */ var _Component2 = _dereq_('./component'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_import); /** * Display that an error has occurred making the video unplayable * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class ErrorDisplay */ var ErrorDisplay = (function (_Component) { function ErrorDisplay(player, options) { _classCallCheck(this, ErrorDisplay); _Component.call(this, player, options); this.update(); this.on(player, 'error', this.update); } _inherits(ErrorDisplay, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ ErrorDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-error-display' }); this.contentEl_ = Dom.createEl('div'); el.appendChild(this.contentEl_); return el; }; /** * Update the error message in localized language * * @method update */ ErrorDisplay.prototype.update = function update() { if (this.player().error()) { this.contentEl_.innerHTML = this.localize(this.player().error().message); } }; return ErrorDisplay; })(_Component3['default']); _Component3['default'].registerComponent('ErrorDisplay', ErrorDisplay); exports['default'] = ErrorDisplay; module.exports = exports['default']; },{"./component":52,"./utils/dom.js":111}],83:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file event-target.js */ var _import = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_import); var EventTarget = function EventTarget() {}; EventTarget.prototype.allowedEvents_ = {}; EventTarget.prototype.on = function (type, fn) { // Remove the addEventListener alias before calling Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = Function.prototype; Events.on(this, type, fn); this.addEventListener = ael; }; EventTarget.prototype.addEventListener = EventTarget.prototype.on; EventTarget.prototype.off = function (type, fn) { Events.off(this, type, fn); }; EventTarget.prototype.removeEventListener = EventTarget.prototype.off; EventTarget.prototype.one = function (type, fn) { Events.one(this, type, fn); }; EventTarget.prototype.trigger = function (event) { var type = event.type || event; if (typeof event === 'string') { event = { type: type }; } event = Events.fixEvent(event); if (this.allowedEvents_[type] && this['on' + type]) { this['on' + type](event); } Events.trigger(this, event); }; // The standard DOM EventTarget.dispatchEvent() is aliased to trigger() EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger; exports['default'] = EventTarget; module.exports = exports['default']; },{"./utils/events.js":112}],84:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; var _log = _dereq_('./utils/log'); var _log2 = _interopRequireWildcard(_log); /* * @file extends.js * * A combination of node inherits and babel's inherits (after transpile). * Both work the same but node adds `super_` to the subClass * and Bable adds the superClass as __proto__. Both seem useful. */ var _inherits = 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) { // node subClass.super_ = superClass; } }; /* * Function for subclassing using the same inheritance that * videojs uses internally * ```js * var Button = videojs.getComponent('Button'); * ``` * ```js * var MyButton = videojs.extends(Button, { * constructor: function(player, options) { * Button.call(this, player, options); * }, * onClick: function() { * // doSomething * } * }); * ``` */ var extendsFn = function extendsFn(superClass) { var subClassMethods = arguments[1] === undefined ? {} : arguments[1]; var subClass = function subClass() { superClass.apply(this, arguments); }; var methods = {}; if (typeof subClassMethods === 'object') { if (typeof subClassMethods.init === 'function') { _log2['default'].warn('Constructor logic via init() is deprecated; please use constructor() instead.'); subClassMethods.constructor = subClassMethods.init; } if (subClassMethods.constructor !== Object.prototype.constructor) { subClass = subClassMethods.constructor; } methods = subClassMethods; } else if (typeof subClassMethods === 'function') { subClass = subClassMethods; } _inherits(subClass, superClass); // Extend subObj's prototype with functions and other properties from props for (var name in methods) { if (methods.hasOwnProperty(name)) { subClass.prototype[name] = methods[name]; } } return subClass; }; exports['default'] = extendsFn; module.exports = exports['default']; },{"./utils/log":116}],85:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file fullscreen-api.js */ var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); /* * Store the browser-specific methods for the fullscreen API * @type {Object|undefined} * @private */ var FullscreenApi = {}; // browser API methods // map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js var apiMap = [ // Spec: https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html ['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'], // WebKit ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Old WebKit (Safari 5.1) ['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Mozilla ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'], // Microsoft ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']]; var specApi = apiMap[0]; var browserApi = undefined; // determine the supported set of functions for (var i = 0; i < apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in _document2['default']) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names if (browserApi) { for (var i = 0; i < browserApi.length; i++) { FullscreenApi[specApi[i]] = browserApi[i]; } } exports['default'] = FullscreenApi; module.exports = exports['default']; },{"global/document":1}],86:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file global-options.js */ var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var navigator = _window2['default'].navigator; /* * Global Player instance options, surfaced from Player.prototype.options_ * options = Player.prototype.options_ * All options should use string keys so they avoid * renaming by closure compiler * * @type {Object} */ exports['default'] = { // Default order of fallback technology techOrder: ['html5', 'flash'], // techOrder: ['flash','html5'], html5: {}, flash: {}, // defaultVolume: 0.85, defaultVolume: 0, // The freakin seaguls are driving me crazy! // default inactivity timeout inactivityTimeout: 2000, // default playback rates playbackRates: [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], // Included control sets children: { mediaLoader: {}, posterImage: {}, textTrackDisplay: {}, loadingSpinner: {}, bigPlayButton: {}, controlBar: {}, errorDisplay: {}, textTrackSettings: {} }, language: _document2['default'].getElementsByTagName('html')[0].getAttribute('lang') || navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language || 'en', // locales and their language translations languages: {}, // Default message to show when a video cannot be played. notSupportedMessage: 'No compatible source was found for this video.' }; module.exports = exports['default']; },{"global/document":1,"global/window":2}],87:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file loading-spinner.js */ var _Component2 = _dereq_('./component'); var _Component3 = _interopRequireWildcard(_Component2); /* Loading Spinner ================================================================================ */ /** * Loading spinner for waiting events * * @extends Component * @class LoadingSpinner */ var LoadingSpinner = (function (_Component) { function LoadingSpinner() { _classCallCheck(this, LoadingSpinner); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(LoadingSpinner, _Component); /** * Create the component's DOM element * * @method createEl */ LoadingSpinner.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner' }); }; return LoadingSpinner; })(_Component3['default']); _Component3['default'].registerComponent('LoadingSpinner', LoadingSpinner); exports['default'] = LoadingSpinner; module.exports = exports['default']; },{"./component":52}],88:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file media-error.js */ var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); /* * Custom MediaError to mimic the HTML5 MediaError * * @param {Number} code The media error code */ var MediaError = (function (_MediaError) { function MediaError(_x) { return _MediaError.apply(this, arguments); } MediaError.toString = function () { return _MediaError.toString(); }; return MediaError; })(function (code) { if (typeof code === 'number') { this.code = code; } else if (typeof code === 'string') { // default code is zero, so this is a custom error this.message = code; } else if (typeof code === 'object') { // object _assign2['default'](this, code); } if (!this.message) { this.message = MediaError.defaultMessages[this.code] || ''; } }); /* * The error code that refers two one of the defined * MediaError types * * @type {Number} */ MediaError.prototype.code = 0; /* * An optional message to be shown with the error. * Message is not part of the HTML5 video spec * but allows for more informative custom errors. * * @type {String} */ MediaError.prototype.message = ''; /* * An optional status code that can be set by plugins * to allow even more detail about the error. * For example the HLS plugin might provide the specific * HTTP status code that was returned when the error * occurred, then allowing a custom error overlay * to display more information. * * @type {Array} */ MediaError.prototype.status = null; MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', // = 0 'MEDIA_ERR_ABORTED', // = 1 'MEDIA_ERR_NETWORK', // = 2 'MEDIA_ERR_DECODE', // = 3 'MEDIA_ERR_SRC_NOT_SUPPORTED', // = 4 'MEDIA_ERR_ENCRYPTED' // = 5 ]; MediaError.defaultMessages = { 1: 'You aborted the video playback', 2: 'A network error caused the video download to fail part-way.', 3: 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support.', 4: 'The video could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The video is encrypted and we do not have the keys to decrypt it.' }; // Add types as properties on MediaError // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4; for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) { MediaError[MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance MediaError.prototype[MediaError.errorTypes[errNum]] = errNum; } exports['default'] = MediaError; module.exports = exports['default']; },{"object.assign":44}],89:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file menu-button.js */ var _Button2 = _dereq_('../button.js'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _Menu = _dereq_('./menu.js'); var _Menu2 = _interopRequireWildcard(_Menu); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import2); var _toTitleCase = _dereq_('../utils/to-title-case.js'); var _toTitleCase2 = _interopRequireWildcard(_toTitleCase); /** * A button class with a popup menu * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MenuButton */ var MenuButton = (function (_Button) { function MenuButton(player) { var options = arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, MenuButton); _Button.call(this, player, options); this.update(); this.on('keydown', this.handleKeyPress); this.el_.setAttribute('aria-haspopup', true); this.el_.setAttribute('role', 'button'); } _inherits(MenuButton, _Button); /** * Update menu * * @method update */ MenuButton.prototype.update = function update() { var menu = this.createMenu(); if (this.menu) { this.removeChild(this.menu); } this.menu = menu; this.addChild(menu); /** * Track the state of the menu button * * @type {Boolean} * @private */ this.buttonPressed_ = false; if (this.items && this.items.length === 0) { this.hide(); } else if (this.items && this.items.length > 1) { this.show(); } }; /** * Create menu * * @return {Menu} The constructed menu * @method createMenu */ MenuButton.prototype.createMenu = function createMenu() { var menu = new _Menu2['default'](this.player_); // Add a title list item to the top if (this.options_.title) { menu.contentEl().appendChild(Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: _toTitleCase2['default'](this.options_.title), tabIndex: -1 })); } this.items = this.createItems(); if (this.items) { // Add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.addItem(this.items[i]); } } return menu; }; /** * Create the list of menu items. Specific to each subclass. * * @method createItems */ MenuButton.prototype.createItems = function createItems() {}; /** * Create the component's DOM element * * @return {Element} * @method createEl */ MenuButton.prototype.createEl = function createEl() { return _Button.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ MenuButton.prototype.buildCSSClass = function buildCSSClass() { var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether. if (this.options_.inline === true) { menuButtonClass += '-inline'; } else { menuButtonClass += '-popup'; } return 'vjs-menu-button ' + menuButtonClass + ' ' + _Button.prototype.buildCSSClass.call(this); }; /** * Focus - Add keyboard functionality to element * This function is not needed anymore. Instead, the * keyboard functionality is handled by * treating the button as triggering a submenu. * When the button is pressed, the submenu * appears. Pressing the button again makes * the submenu disappear. * * @method handleFocus */ MenuButton.prototype.handleFocus = function handleFocus() {}; /** * Can't turn off list display that we turned * on with focus, because list would go away. * * @method handleBlur */ MenuButton.prototype.handleBlur = function handleBlur() {}; /** * When you click the button it adds focus, which * will show the menu indefinitely. * So we'll remove focus when the mouse leaves the button. * Focus is needed for tab navigation. * Allow sub components to stack CSS class names * * @method handleClick */ MenuButton.prototype.handleClick = function handleClick() { this.one('mouseout', Fn.bind(this, function () { this.menu.unlockShowing(); this.el_.blur(); })); if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } }; /** * Handle key press on menu * * @param {Object} Key press event * @method handleKeyPress */ MenuButton.prototype.handleKeyPress = function handleKeyPress(event) { // Check for space bar (32) or enter (13) keys if (event.which === 32 || event.which === 13) { if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } event.preventDefault(); // Check for escape (27) key } else if (event.which === 27) { if (this.buttonPressed_) { this.unpressButton(); } event.preventDefault(); } }; /** * Makes changes based on button pressed * * @method pressButton */ MenuButton.prototype.pressButton = function pressButton() { this.buttonPressed_ = true; this.menu.lockShowing(); this.el_.setAttribute('aria-pressed', true); if (this.items && this.items.length > 0) { this.items[0].el().focus(); // set the focus to the title of the submenu } }; /** * Makes changes based on button unpressed * * @method unpressButton */ MenuButton.prototype.unpressButton = function unpressButton() { this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-pressed', false); }; return MenuButton; })(_Button3['default']); _Component2['default'].registerComponent('MenuButton', MenuButton); exports['default'] = MenuButton; module.exports = exports['default']; },{"../button.js":51,"../component.js":52,"../utils/dom.js":111,"../utils/fn.js":113,"../utils/to-title-case.js":119,"./menu.js":91}],90:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file menu-item.js */ var _Button2 = _dereq_('../button.js'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); /** * The component for a menu item. `<li>` * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MenuItem */ var MenuItem = (function (_Button) { function MenuItem(player, options) { _classCallCheck(this, MenuItem); _Button.call(this, player, options); this.selected(options.selected); } _inherits(MenuItem, _Button); /** * Create the component's DOM element * * @param {String=} type Desc * @param {Object=} props Desc * @return {Element} * @method createEl */ MenuItem.prototype.createEl = function createEl(type, props) { return _Button.prototype.createEl.call(this, 'li', _assign2['default']({ className: 'vjs-menu-item', innerHTML: this.localize(this.options_.label) }, props)); }; /** * Handle a click on the menu item, and set it to selected * * @method handleClick */ MenuItem.prototype.handleClick = function handleClick() { this.selected(true); }; /** * Set this menu item as selected or not * * @param {Boolean} selected * @method selected */ MenuItem.prototype.selected = (function (_selected) { function selected(_x) { return _selected.apply(this, arguments); } selected.toString = function () { return _selected.toString(); }; return selected; })(function (selected) { if (selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-selected', true); } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-selected', false); } }); return MenuItem; })(_Button3['default']); _Component2['default'].registerComponent('MenuItem', MenuItem); exports['default'] = MenuItem; module.exports = exports['default']; },{"../button.js":51,"../component.js":52,"object.assign":44}],91:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file menu.js */ var _Component2 = _dereq_('../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import2); var _import3 = _dereq_('../utils/events.js'); var Events = _interopRequireWildcard(_import3); /** * The Menu component is used to build pop up menus, including subtitle and * captions selection menus. * * @extends Component * @class Menu */ var Menu = (function (_Component) { function Menu() { _classCallCheck(this, Menu); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(Menu, _Component); /** * Add a menu item to the menu * * @param {Object|String} component Component or component type to add * @method addItem */ Menu.prototype.addItem = function addItem(component) { this.addChild(component); component.on('click', Fn.bind(this, function () { this.unlockShowing(); })); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Menu.prototype.createEl = function createEl() { var contentElType = this.options_.contentElType || 'ul'; this.contentEl_ = Dom.createEl(contentElType, { className: 'vjs-menu-content' }); var el = _Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons, // where a click on the parent is significant Events.on(el, 'click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; return Menu; })(_Component3['default']); _Component3['default'].registerComponent('Menu', Menu); exports['default'] = Menu; module.exports = exports['default']; },{"../component.js":52,"../utils/dom.js":111,"../utils/events.js":112,"../utils/fn.js":113}],92:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file player.js */ // Subclasses Component var _Component2 = _dereq_('./component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _import = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_import); var _import2 = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_import2); var _import3 = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_import3); var _import4 = _dereq_('./utils/guid.js'); var Guid = _interopRequireWildcard(_import4); var _import5 = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_import5); var _log = _dereq_('./utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _toTitleCase = _dereq_('./utils/to-title-case.js'); var _toTitleCase2 = _interopRequireWildcard(_toTitleCase); var _createTimeRange = _dereq_('./utils/time-ranges.js'); var _bufferedPercent2 = _dereq_('./utils/buffer.js'); var _FullscreenApi = _dereq_('./fullscreen-api.js'); var _FullscreenApi2 = _interopRequireWildcard(_FullscreenApi); var _MediaError = _dereq_('./media-error.js'); var _MediaError2 = _interopRequireWildcard(_MediaError); var _globalOptions = _dereq_('./global-options.js'); var _globalOptions2 = _interopRequireWildcard(_globalOptions); var _safeParseTuple2 = _dereq_('safe-json-parse/tuple'); var _safeParseTuple3 = _interopRequireWildcard(_safeParseTuple2); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); var _mergeOptions = _dereq_('./utils/merge-options.js'); var _mergeOptions2 = _interopRequireWildcard(_mergeOptions); // Include required child components (importing also registers them) var _MediaLoader = _dereq_('./tech/loader.js'); var _MediaLoader2 = _interopRequireWildcard(_MediaLoader); var _PosterImage = _dereq_('./poster-image.js'); var _PosterImage2 = _interopRequireWildcard(_PosterImage); var _TextTrackDisplay = _dereq_('./tracks/text-track-display.js'); var _TextTrackDisplay2 = _interopRequireWildcard(_TextTrackDisplay); var _LoadingSpinner = _dereq_('./loading-spinner.js'); var _LoadingSpinner2 = _interopRequireWildcard(_LoadingSpinner); var _BigPlayButton = _dereq_('./big-play-button.js'); var _BigPlayButton2 = _interopRequireWildcard(_BigPlayButton); var _ControlBar = _dereq_('./control-bar/control-bar.js'); var _ControlBar2 = _interopRequireWildcard(_ControlBar); var _ErrorDisplay = _dereq_('./error-display.js'); var _ErrorDisplay2 = _interopRequireWildcard(_ErrorDisplay); var _TextTrackSettings = _dereq_('./tracks/text-track-settings.js'); var _TextTrackSettings2 = _interopRequireWildcard(_TextTrackSettings); // Require html5 tech, at least for disposing the original video tag var _Html5 = _dereq_('./tech/html5.js'); var _Html52 = _interopRequireWildcard(_Html5); /** * An instance of the `Player` class is created when any of the Video.js setup methods are used to initialize a video. * ```js * var myPlayer = videojs('example_video_1'); * ``` * In the following example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready. * ```html * <video id="example_video_1" data-setup='{}' controls> * <source src="my-source.mp4" type="video/mp4"> * </video> * ``` * After an instance has been created it can be accessed globally using `Video('example_video_1')`. * * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class Player */ var Player = (function (_Component) { /** * player's constructor function * * @constructs * @method init * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Player options * @param {Function=} ready Ready callback function */ function Player(tag, options, ready) { var _this = this; _classCallCheck(this, Player); // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + Guid.newGUID(); // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = _assign2['default'](Player.getTagSettings(tag), options); // Delay the initialization of children because we need to set up // player properties first, and can't use `this` before `super()` options.initChildren = false; // Same with creating the element options.createEl = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Run base component initializing with new options _Component.call(this, null, options, ready); // if the global option object was accidentally blown away by // someone, bail early with an informative error if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) { throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?'); } this.tag = tag; // Store the original tag used to set options // Store the tag attributes used to restore html5 element this.tagAttributes = tag && Dom.getElAttributes(tag); // Update current language this.language(options.language || _globalOptions2['default'].language); // Update Supported Languages if (options.languages) { (function () { // Normalise player option languages to lowercase var languagesToLower = {}; Object.getOwnPropertyNames(options.languages).forEach(function (name) { languagesToLower[name.toLowerCase()] = options.languages[name]; }); _this.languages_ = languagesToLower; })(); } else { this.languages_ = _globalOptions2['default'].languages; } // Cache for video property values. this.cache_ = {}; // Set poster this.poster_ = options.poster || ''; // Set controls this.controls_ = !!options.controls; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; /* * Store the internal state of scrubbing * * @private * @return {Boolean} True if the user is scrubbing */ this.scrubbing_ = false; this.el_ = this.createEl(); // We also want to pass the original player options to each component and plugin // as well so they don't need to reach back into the player for options later. // We also need to do another copy of this.options_ so we don't end up with // an infinite loop. var playerOptionsCopy = _mergeOptions2['default']({}, this.options_); // Load plugins if (options.plugins) { (function () { var plugins = options.plugins; Object.getOwnPropertyNames(plugins).forEach(function (name) { plugins[name].playerOptions = playerOptionsCopy; if (typeof this[name] === 'function') { this[name](plugins[name]); } else { _log2['default'].error('Unable to find plugin:', name); } }, _this); })(); } this.options_.playerOptions = playerOptionsCopy; this.initChildren(); // Set isAudio based on whether or not an audio tag was used this.isAudio(tag.nodeName.toLowerCase() === 'audio'); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (this.controls()) { this.addClass('vjs-controls-enabled'); } else { this.addClass('vjs-controls-disabled'); } if (this.isAudio()) { this.addClass('vjs-audio'); } if (this.flexNotSupported_()) { this.addClass('vjs-no-flex'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (browser.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // Make player easily findable by ID Player.players[this.id_] = this; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed this.userActive_ = true; this.reportUserActivity(); this.listenForUserActivity(); this.on('fullscreenchange', this.handleFullscreenChange); this.on('stageclick', this.handleStageClick); } _inherits(Player, _Component); /** * Destroys the video player and does any necessary cleanup * ```js * myPlayer.dispose(); * ``` * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. * * @method dispose */ Player.prototype.dispose = function dispose() { this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); // Kill reference to this player Player.players[this.id_] = null; if (this.tag && this.tag.player) { this.tag.player = null; } if (this.el_ && this.el_.player) { this.el_.player = null; } if (this.tech) { this.tech.dispose(); } _Component.prototype.dispose.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Player.prototype.createEl = function createEl() { var el = this.el_ = _Component.prototype.createEl.call(this, 'div'); var tag = this.tag; // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag var attrs = Dom.getElAttributes(tag); Object.getOwnPropertyNames(attrs).forEach(function (attr) { // workaround so we don't totally break IE7 // http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7 if (attr === 'class') { el.className = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } }); // Update tag id/class for use as HTML5 playback tech // Might think we should do this after embedding in container so .vjs-tech class // doesn't flash 100% width/height, but class only applies with .video-js parent tag.id += '_html5_api'; tag.className = 'vjs-tech'; // Make player findable on elements tag.player = el.player = this; // Default state of video is paused this.addClass('vjs-paused'); // Add a style element in the player that we'll use to set the width/height // of the player in a way that's still overrideable by CSS, just like the // video element this.styleEl_ = _document2['default'].createElement('style'); el.appendChild(this.styleEl_); // Pass in the width/height/aspectRatio options which will update the style el this.width(this.options_.width); this.height(this.options_.height); this.fluid(this.options_.fluid); this.aspectRatio(this.options_.aspectRatio); // insertElFirst seems to cause the networkState to flicker from 3 to 2, so // keep track of the original for later so we can know if the source originally failed tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container if (tag.parentNode) { tag.parentNode.insertBefore(el, tag); } Dom.insertElFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup. this.el_ = el; return el; }; /** * Get/set player width * * @param {Number=} value Value for width * @return {Number} Width when getting * @method width */ Player.prototype.width = function width(value) { return this.dimension('width', value); }; /** * Get/set player height * * @param {Number=} value Value for height * @return {Number} Height when getting * @method height */ Player.prototype.height = function height(value) { return this.dimension('height', value); }; /** * Get/set dimension for player * * @param {String} dimension Either width or height * @param {Number=} value Value for dimension * @return {Component} * @method dimension */ Player.prototype.dimension = (function (_dimension) { function dimension(_x, _x2) { return _dimension.apply(this, arguments); } dimension.toString = function () { return _dimension.toString(); }; return dimension; })(function (dimension, value) { var privDimension = dimension + '_'; if (value === undefined) { return this[privDimension] || 0; } if (value === '') { // If an empty string is given, reset the dimension to be automatic this[privDimension] = undefined; } else { var parsedVal = parseFloat(value); if (isNaN(parsedVal)) { _log2['default'].error('Improper value "' + value + '" supplied for for ' + dimension); return this; } this[privDimension] = parsedVal; } this.updateStyleEl_(); return this; }); /** * Add/remove the vjs-fluid class * * @param {Boolean} bool Value of true adds the class, value of false removes the class * @method fluid */ Player.prototype.fluid = function fluid(bool) { if (bool === undefined) { return !!this.fluid_; } this.fluid_ = !!bool; if (bool) { this.addClass('vjs-fluid'); } else { this.removeClass('vjs-fluid'); } }; /** * Get/Set the aspect ratio * * @param {String=} ratio Aspect ratio for player * @return aspectRatio * @method aspectRatio */ Player.prototype.aspectRatio = function aspectRatio(ratio) { if (ratio === undefined) { return this.aspectRatio_; } // Check for width:height format if (!/^\d+\:\d+$/.test(ratio)) { throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.'); } this.aspectRatio_ = ratio; // We're assuming if you set an aspect ratio you want fluid mode, // because in fixed mode you could calculate width and height yourself. this.fluid(true); this.updateStyleEl_(); }; /** * Update styles of the player element (height, width and aspect ratio) * * @method updateStyleEl_ */ Player.prototype.updateStyleEl_ = function updateStyleEl_() { var width = undefined; var height = undefined; var aspectRatio = undefined; // The aspect ratio is either used directly or to calculate width and height. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') { // Use any aspectRatio that's been specifically set aspectRatio = this.aspectRatio_; } else if (this.videoWidth()) { // Otherwise try to get the aspect ratio from the video metadata aspectRatio = this.videoWidth() + ':' + this.videoHeight(); } else { // Or use a default. The video element's is 2:1, but 16:9 is more common. aspectRatio = '16:9'; } // Get the ratio as a decimal we can use to calculate dimensions var ratioParts = aspectRatio.split(':'); var ratioMultiplier = ratioParts[1] / ratioParts[0]; if (this.width_ !== undefined) { // Use any width that's been specifically set width = this.width_; } else if (this.height_ !== undefined) { // Or calulate the width from the aspect ratio if a height has been set width = this.height_ / ratioMultiplier; } else { // Or use the video's metadata, or use the video el's default of 300 width = this.videoWidth() || 300; } if (this.height_ !== undefined) { // Use any height that's been specifically set height = this.height_; } else { // Otherwise calculate the height from the ratio and the width height = width * ratioMultiplier; } var idClass = this.id() + '-dimensions'; // Ensure the right class is still on the player for the style element this.addClass(idClass); // Create the width/height CSS var css = '.' + idClass + ' { width: ' + width + 'px; height: ' + height + 'px; }'; // Add the aspect ratio CSS for when using a fluid layout css += '.' + idClass + '.vjs-fluid { padding-top: ' + ratioMultiplier * 100 + '%; }'; // Update the style el if (this.styleEl_.styleSheet) { this.styleEl_.styleSheet.cssText = css; } else { this.styleEl_.innerHTML = css; } }; /** * Load the Media Playback Technology (tech) * Load/Create an instance of playback technology including element and API methods * And append playback element in player div. * * @param {String} techName Name of the playback technology * @param {String} source Video source * @method loadTech */ Player.prototype.loadTech = function loadTech(techName, source) { // Pause and remove current playback technology if (this.tech) { this.unloadTech(); } // get rid of the HTML5 video tag as soon as we are using another tech if (techName !== 'Html5' && this.tag) { _Component3['default'].getComponent('Html5').disposeMediaElement(this.tag); this.tag.player = null; this.tag = null; } this.techName = techName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; var techReady = Fn.bind(this, function () { this.triggerReady(); }); // Grab tech-specific options from player options and add source and parent element to use. var techOptions = _assign2['default']({ source: source, playerId: this.id(), techId: '' + this.id() + '_' + techName + '_api', textTracks: this.textTracks_, autoplay: this.options_.autoplay, preload: this.options_.preload, loop: this.options_.loop, muted: this.options_.muted, poster: this.poster(), language: this.language() }, this.options_[techName.toLowerCase()]); if (this.tag) { techOptions.tag = this.tag; } if (source) { this.currentType_ = source.type; if (source.src === this.cache_.src && this.cache_.currentTime > 0) { techOptions.startTime = this.cache_.currentTime; } this.cache_.src = source.src; } // Initialize tech instance var techComponent = _Component3['default'].getComponent(techName); this.tech = new techComponent(techOptions); this.on(this.tech, 'ready', this.handleTechReady); this.on(this.tech, 'usenativecontrols', this.handleTechUseNativeControls); // Listen to every HTML5 events and trigger them back on the player for the plugins this.on(this.tech, 'loadstart', this.handleTechLoadStart); this.on(this.tech, 'waiting', this.handleTechWaiting); this.on(this.tech, 'canplay', this.handleTechCanPlay); this.on(this.tech, 'canplaythrough', this.handleTechCanPlayThrough); this.on(this.tech, 'playing', this.handleTechPlaying); this.on(this.tech, 'ended', this.handleTechEnded); this.on(this.tech, 'seeking', this.handleTechSeeking); this.on(this.tech, 'seeked', this.handleTechSeeked); this.on(this.tech, 'play', this.handleTechPlay); this.on(this.tech, 'firstplay', this.handleTechFirstPlay); this.on(this.tech, 'pause', this.handleTechPause); this.on(this.tech, 'progress', this.handleTechProgress); this.on(this.tech, 'durationchange', this.handleTechDurationChange); this.on(this.tech, 'fullscreenchange', this.handleTechFullscreenChange); this.on(this.tech, 'error', this.handleTechError); this.on(this.tech, 'suspend', this.handleTechSuspend); this.on(this.tech, 'abort', this.handleTechAbort); this.on(this.tech, 'emptied', this.handleTechEmptied); this.on(this.tech, 'stalled', this.handleTechStalled); this.on(this.tech, 'loadedmetadata', this.handleTechLoadedMetaData); this.on(this.tech, 'loadeddata', this.handleTechLoadedData); this.on(this.tech, 'timeupdate', this.handleTechTimeUpdate); this.on(this.tech, 'ratechange', this.handleTechRateChange); this.on(this.tech, 'volumechange', this.handleTechVolumeChange); this.on(this.tech, 'texttrackchange', this.onTextTrackChange); this.on(this.tech, 'loadedmetadata', this.updateStyleEl_); if (this.controls() && !this.usingNativeControls()) { this.addTechControlsListeners(); } // Add the tech element in the DOM if it was not already there // Make sure to not insert the original video element if using Html5 if (this.tech.el().parentNode !== this.el() && (techName !== 'Html5' || !this.tag)) { Dom.insertElFirst(this.tech.el(), this.el()); } // Get rid of the original video tag reference after the first tech is loaded if (this.tag) { this.tag.player = null; this.tag = null; } this.tech.ready(techReady); }; /** * Unload playback technology * * @method unloadTech */ Player.prototype.unloadTech = function unloadTech() { // Save the current text tracks so that we can reuse the same text tracks with the next tech this.textTracks_ = this.textTracks(); this.isReady_ = false; this.tech.dispose(); this.tech = false; }; /** * Add playback technology listeners * * @method addTechControlsListeners */ Player.prototype.addTechControlsListeners = function addTechControlsListeners() { // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on(this.tech, 'mousedown', this.handleTechClick); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on(this.tech, 'touchstart', this.handleTechTouchStart); this.on(this.tech, 'touchmove', this.handleTechTouchMove); this.on(this.tech, 'touchend', this.handleTechTouchEnd); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on(this.tech, 'tap', this.handleTechTap); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. * * @method removeTechControlsListeners */ Player.prototype.removeTechControlsListeners = function removeTechControlsListeners() { // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off(this.tech, 'tap', this.handleTechTap); this.off(this.tech, 'touchstart', this.handleTechTouchStart); this.off(this.tech, 'touchmove', this.handleTechTouchMove); this.off(this.tech, 'touchend', this.handleTechTouchEnd); this.off(this.tech, 'mousedown', this.handleTechClick); }; /** * Player waits for the tech to be ready * * @private * @method handleTechReady */ Player.prototype.handleTechReady = function handleTechReady() { this.triggerReady(); // Keep the same volume as before if (this.cache_.volume) { this.techCall('setVolume', this.cache_.volume); } // Chrome and Safari both have issues with autoplay. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays) // This fixes both issues. Need to wait for API, so it updates displays correctly if (this.tag && this.options_.autoplay && this.paused()) { delete this.tag.poster; // Chrome Fix. Fixed in Chrome v16. this.play(); } }; /** * Fired when the native controls are used * * @private * @method handleTechUseNativeControls */ Player.prototype.handleTechUseNativeControls = function handleTechUseNativeControls() { this.usingNativeControls(true); }; /** * Fired when the user agent begins looking for media data * * @event loadstart */ Player.prototype.handleTechLoadStart = function handleTechLoadStart() { // TODO: Update to use `emptied` event instead. See #1277. this.removeClass('vjs-ended'); // reset the error state this.error(null); // If it's already playing we want to trigger a firstplay event now. // The firstplay event relies on both the play and loadstart events // which can happen in any order for a new source if (!this.paused()) { this.trigger('loadstart'); this.trigger('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); this.trigger('loadstart'); } }; /** * Add/remove the vjs-has-started class * * @param {Boolean} hasStarted The value of true adds the class the value of false remove the class * @return {Boolean} Boolean value if has started * @method hasStarted */ Player.prototype.hasStarted = (function (_hasStarted) { function hasStarted(_x3) { return _hasStarted.apply(this, arguments); } hasStarted.toString = function () { return _hasStarted.toString(); }; return hasStarted; })(function (hasStarted) { if (hasStarted !== undefined) { // only update if this is a new value if (this.hasStarted_ !== hasStarted) { this.hasStarted_ = hasStarted; if (hasStarted) { this.addClass('vjs-has-started'); // trigger the firstplay event if this newly has played this.trigger('firstplay'); } else { this.removeClass('vjs-has-started'); } } return this; } return !!this.hasStarted_; }); /** * Fired whenever the media begins or resumes playback * * @event play */ Player.prototype.handleTechPlay = function handleTechPlay() { this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // hide the poster when the user hits play // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play this.hasStarted(true); this.trigger('play'); }; /** * Fired whenever the media begins waiting * * @event waiting */ Player.prototype.handleTechWaiting = function handleTechWaiting() { this.addClass('vjs-waiting'); this.trigger('waiting'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @event canplay */ Player.prototype.handleTechCanPlay = function handleTechCanPlay() { this.removeClass('vjs-waiting'); this.trigger('canplay'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @event canplaythrough */ Player.prototype.handleTechCanPlayThrough = function handleTechCanPlayThrough() { this.removeClass('vjs-waiting'); this.trigger('canplaythrough'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @event playing */ Player.prototype.handleTechPlaying = function handleTechPlaying() { this.removeClass('vjs-waiting'); this.trigger('playing'); }; /** * Fired whenever the player is jumping to a new time * * @event seeking */ Player.prototype.handleTechSeeking = function handleTechSeeking() { this.addClass('vjs-seeking'); this.trigger('seeking'); }; /** * Fired when the player has finished jumping to a new time * * @event seeked */ Player.prototype.handleTechSeeked = function handleTechSeeked() { this.removeClass('vjs-seeking'); this.trigger('seeked'); }; /** * Fired the first time a video is played * Not part of the HLS spec, and we're not sure if this is the best * implementation yet, so use sparingly. If you don't have a reason to * prevent playback, use `myPlayer.one('play');` instead. * * @event firstplay */ Player.prototype.handleTechFirstPlay = function handleTechFirstPlay() { //If the first starttime attribute is specified //then we will start at the given offset in seconds if (this.options_.starttime) { this.currentTime(this.options_.starttime); } this.addClass('vjs-has-started'); this.trigger('firstplay'); }; /** * Fired whenever the media has been paused * * @event pause */ Player.prototype.handleTechPause = function handleTechPause() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.trigger('pause'); }; /** * Fired while the user agent is downloading media data * * @event progress */ Player.prototype.handleTechProgress = function handleTechProgress() { this.trigger('progress'); // Add custom event for when source is finished downloading. if (this.bufferedPercent() === 1) { this.trigger('loadedalldata'); } }; /** * Fired when the end of the media resource is reached (currentTime == duration) * * @event ended */ Player.prototype.handleTechEnded = function handleTechEnded() { this.addClass('vjs-ended'); if (this.options_.loop) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } this.trigger('ended'); }; /** * Fired when the duration of the media resource is first known or changed * * @event durationchange */ Player.prototype.handleTechDurationChange = function handleTechDurationChange() { this.updateDuration(); this.trigger('durationchange'); }; /** * Handle a click on the media element to play/pause * * @param {Object=} event Event object * @method handleTechClick */ Player.prototype.handleTechClick = function handleTechClick(event) { // We're using mousedown to detect clicks thanks to Flash, but mousedown // will also be triggered with right-clicks, so we need to prevent that if (event.button !== 0) { return; } // When controls are disabled a click should not toggle playback because // the click is considered a control if (this.controls()) { if (this.paused()) { this.play(); } else { this.pause(); } } }; /** * Handle a tap on the media element. It will toggle the user * activity state, which hides and shows the controls. * * @method handleTechTap */ Player.prototype.handleTechTap = function handleTechTap() { this.userActive(!this.userActive()); }; /** * Handle touch to start * * @method handleTechTouchStart */ Player.prototype.handleTechTouchStart = function handleTechTouchStart() { this.userWasActive = this.userActive(); }; /** * Handle touch to move * * @method handleTechTouchMove */ Player.prototype.handleTechTouchMove = function handleTechTouchMove() { if (this.userWasActive) { this.reportUserActivity(); } }; /** * Handle touch to end * * @method handleTechTouchEnd */ Player.prototype.handleTechTouchEnd = function handleTechTouchEnd(event) { // Stop the mouse events from also happening event.preventDefault(); }; /** * Update the duration of the player using the tech * * @private * @method updateDuration */ Player.prototype.updateDuration = function updateDuration() { // Allows for caching value instead of asking player each time. // We need to get the techGet response and check for a value so we don't // accidentally cause the stack to blow up. var duration = this.techGet('duration'); if (duration) { if (duration < 0) { duration = Infinity; } this.duration(duration); // Determine if the stream is live and propagate styles down to UI. if (duration === Infinity) { this.addClass('vjs-live'); } else { this.removeClass('vjs-live'); } } }; /** * Fired when the player switches in or out of fullscreen mode * * @event fullscreenchange */ Player.prototype.handleFullscreenChange = function handleFullscreenChange() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; /** * native click events on the SWF aren't triggered on IE11, Win8.1RT * use stageclick events triggered from inside the SWF instead * * @private * @method handleStageClick */ Player.prototype.handleStageClick = function handleStageClick() { this.reportUserActivity(); }; /** * Handle Tech Fullscreen Change * * @method handleTechFullscreenChange */ Player.prototype.handleTechFullscreenChange = function handleTechFullscreenChange(event, data) { if (data) { this.isFullscreen(data.isFullscreen); } this.trigger('fullscreenchange'); }; /** * Fires when an error occurred during the loading of an audio/video * * @event error */ Player.prototype.handleTechError = function handleTechError() { this.error(this.tech.error().code); }; /** * Fires when the browser is intentionally not getting media data * * @event suspend */ Player.prototype.handleTechSuspend = function handleTechSuspend() { this.trigger('suspend'); }; /** * Fires when the loading of an audio/video is aborted * * @event abort */ Player.prototype.handleTechAbort = function handleTechAbort() { this.trigger('abort'); }; /** * Fires when the current playlist is empty * * @event emptied */ Player.prototype.handleTechEmptied = function handleTechEmptied() { this.trigger('emptied'); }; /** * Fires when the browser is trying to get media data, but data is not available * * @event stalled */ Player.prototype.handleTechStalled = function handleTechStalled() { this.trigger('stalled'); }; /** * Fires when the browser has loaded meta data for the audio/video * * @event loadedmetadata */ Player.prototype.handleTechLoadedMetaData = function handleTechLoadedMetaData() { this.trigger('loadedmetadata'); }; /** * Fires when the browser has loaded the current frame of the audio/video * * @event loaddata */ Player.prototype.handleTechLoadedData = function handleTechLoadedData() { this.trigger('loadeddata'); }; /** * Fires when the current playback position has changed * * @event timeupdate */ Player.prototype.handleTechTimeUpdate = function handleTechTimeUpdate() { this.trigger('timeupdate'); }; /** * Fires when the playing speed of the audio/video is changed * * @event ratechange */ Player.prototype.handleTechRateChange = function handleTechRateChange() { this.trigger('ratechange'); }; /** * Fires when the volume has been changed * * @event volumechange */ Player.prototype.handleTechVolumeChange = function handleTechVolumeChange() { this.trigger('volumechange'); }; /** * Fires when the text track has been changed * * @event texttrackchange */ Player.prototype.onTextTrackChange = function onTextTrackChange() { this.trigger('texttrackchange'); }; /** * Get object for cached values. * * @return {Object} * @method getCache */ Player.prototype.getCache = function getCache() { return this.cache_; }; /** * Pass values to the playback tech * * @param {String=} method Method * @param {Object=} arg Argument * @method techCall */ Player.prototype.techCall = function techCall(method, arg) { // If it's not ready yet, call method when it is if (this.tech && !this.tech.isReady_) { this.tech.ready(function () { this[method](arg); }); // Otherwise call method now } else { try { this.tech[method](arg); } catch (e) { _log2['default'](e); throw e; } } }; /** * Get calls can't wait for the tech, and sometimes don't need to. * * @param {String} method Tech method * @return {Method} * @method techGet */ Player.prototype.techGet = function techGet(method) { if (this.tech && this.tech.isReady_) { // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech[method](); } catch (e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech[method] === undefined) { _log2['default']('Video.js: ' + method + ' method not defined for ' + this.techName + ' playback technology.', e); } else { // When a method isn't available on the object it throws a TypeError if (e.name === 'TypeError') { _log2['default']('Video.js: ' + method + ' unavailable on ' + this.techName + ' playback technology element.', e); this.tech.isReady_ = false; } else { _log2['default'](e); } } throw e; } } return; }; /** * start media playback * ```js * myPlayer.play(); * ``` * * @return {Player} self * @method play */ Player.prototype.play = function play() { this.techCall('play'); return this; }; /** * Pause the video playback * ```js * myPlayer.pause(); * ``` * * @return {Player} self * @method pause */ Player.prototype.pause = function pause() { this.techCall('pause'); return this; }; /** * Check if the player is paused * ```js * var isPaused = myPlayer.paused(); * var isPlaying = !myPlayer.paused(); * ``` * * @return {Boolean} false if the media is currently playing, or true otherwise * @method paused */ Player.prototype.paused = function paused() { // The initial state of paused should be true (in Safari it's actually false) return this.techGet('paused') === false ? false : true; }; /** * Returns whether or not the user is "scrubbing". Scrubbing is when the user * has clicked the progress bar handle and is dragging it along the progress bar. * * @param {Boolean} isScrubbing True/false the user is scrubbing * @return {Boolean} The scrubbing status when getting * @return {Object} The player when setting * @method scrubbing */ Player.prototype.scrubbing = function scrubbing(isScrubbing) { if (isScrubbing !== undefined) { this.scrubbing_ = !!isScrubbing; if (isScrubbing) { this.addClass('vjs-scrubbing'); } else { this.removeClass('vjs-scrubbing'); } return this; } return this.scrubbing_; }; /** * Get or set the current time (in seconds) * ```js * // get * var whereYouAt = myPlayer.currentTime(); * // set * myPlayer.currentTime(120); // 2 minutes into the video * ``` * * @param {Number|String=} seconds The time to seek to * @return {Number} The time in seconds, when not setting * @return {Player} self, when the current time is set * @method currentTime */ Player.prototype.currentTime = function currentTime(seconds) { if (seconds !== undefined) { this.techCall('setCurrentTime', seconds); return this; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performance benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. return this.cache_.currentTime = this.techGet('currentTime') || 0; }; /** * Get the length in time of the video in seconds * ```js * var lengthOfVideo = myPlayer.duration(); * ``` * **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @param {Number} seconds Duration when setting * @return {Number} The duration of the video in seconds when getting * @method duration */ Player.prototype.duration = function duration(seconds) { if (seconds !== undefined) { // cache the last set value for optimized scrubbing (esp. Flash) this.cache_.duration = parseFloat(seconds); return this; } if (this.cache_.duration === undefined) { this.updateDuration(); } return this.cache_.duration || 0; }; /** * Calculates how much time is left. * ```js * var timeLeft = myPlayer.remainingTime(); * ``` * Not a native video element function, but useful * * @return {Number} The time remaining in seconds * @method remainingTime */ Player.prototype.remainingTime = function remainingTime() { return this.duration() - this.currentTime(); }; // http://dev.w3.org/html5/spec/video.html#dom-media-buffered // Buffered returns a timerange object. // Kind of like an array of portions of the video that have been downloaded. /** * Get a TimeRange object with the times of the video that have been downloaded * If you just want the percent of the video that's been downloaded, * use bufferedPercent. * ```js * // Number of different ranges of time have been buffered. Usually 1. * numberOfRanges = bufferedTimeRange.length, * // Time in seconds when the first range starts. Usually 0. * firstRangeStart = bufferedTimeRange.start(0), * // Time in seconds when the first range ends * firstRangeEnd = bufferedTimeRange.end(0), * // Length in seconds of the first time range * firstRangeLength = firstRangeEnd - firstRangeStart; * ``` * * @return {Object} A mock TimeRange object (following HTML spec) * @method buffered */ Player.prototype.buffered = (function (_buffered) { function buffered() { return _buffered.apply(this, arguments); } buffered.toString = function () { return _buffered.toString(); }; return buffered; })(function () { var buffered = this.techGet('buffered'); if (!buffered || !buffered.length) { buffered = _createTimeRange.createTimeRange(0, 0); } return buffered; }); /** * Get the percent (as a decimal) of the video that's been downloaded * ```js * var howMuchIsDownloaded = myPlayer.bufferedPercent(); * ``` * 0 means none, 1 means all. * (This method isn't in the HTML5 spec, but it's very convenient) * * @return {Number} A decimal between 0 and 1 representing the percent * @method bufferedPercent */ Player.prototype.bufferedPercent = (function (_bufferedPercent) { function bufferedPercent() { return _bufferedPercent.apply(this, arguments); } bufferedPercent.toString = function () { return _bufferedPercent.toString(); }; return bufferedPercent; })(function () { return _bufferedPercent2.bufferedPercent(this.buffered(), this.duration()); }); /** * Get the ending time of the last buffered time range * This is used in the progress bar to encapsulate all time ranges. * * @return {Number} The end of the last buffered time range * @method bufferedEnd */ Player.prototype.bufferedEnd = function bufferedEnd() { var buffered = this.buffered(), duration = this.duration(), end = buffered.end(buffered.length - 1); if (end > duration) { end = duration; } return end; }; /** * Get or set the current volume of the media * ```js * // get * var howLoudIsIt = myPlayer.volume(); * // set * myPlayer.volume(0.5); // Set volume to half * ``` * 0 is off (muted), 1.0 is all the way up, 0.5 is half way. * * @param {Number} percentAsDecimal The new volume as a decimal percent * @return {Number} The current volume when getting * @return {Player} self when setting * @method volume */ Player.prototype.volume = function volume(percentAsDecimal) { var vol = undefined; if (percentAsDecimal !== undefined) { vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1 this.cache_.volume = vol; this.techCall('setVolume', vol); return this; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet('volume')); return isNaN(vol) ? 1 : vol; }; /** * Get the current muted state, or turn mute on or off * ```js * // get * var isVolumeMuted = myPlayer.muted(); * // set * myPlayer.muted(true); // mute the volume * ``` * * @param {Boolean=} muted True to mute, false to unmute * @return {Boolean} True if mute is on, false if not when getting * @return {Player} self when setting mute * @method muted */ Player.prototype.muted = (function (_muted) { function muted(_x4) { return _muted.apply(this, arguments); } muted.toString = function () { return _muted.toString(); }; return muted; })(function (muted) { if (muted !== undefined) { this.techCall('setMuted', muted); return this; } return this.techGet('muted') || false; // Default to false }); // Check if current tech can support native fullscreen // (e.g. with built in controls like iOS, so not our flash swf) /** * Check to see if fullscreen is supported * * @return {Boolean} * @method supportsFullScreen */ Player.prototype.supportsFullScreen = function supportsFullScreen() { return this.techGet('supportsFullScreen') || false; }; /** * Check if the player is in fullscreen mode * ```js * // get * var fullscreenOrNot = myPlayer.isFullscreen(); * // set * myPlayer.isFullscreen(true); // tell the player it's in fullscreen * ``` * NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official * property and instead document.fullscreenElement is used. But isFullscreen is * still a valuable property for internal player workings. * * @param {Boolean=} isFS Update the player's fullscreen state * @return {Boolean} true if fullscreen false if not when getting * @return {Player} self when setting * @method isFullscreen */ Player.prototype.isFullscreen = function isFullscreen(isFS) { if (isFS !== undefined) { this.isFullscreen_ = !!isFS; return this; } return !!this.isFullscreen_; }; /** * Increase the size of the video to full screen * ```js * myPlayer.requestFullscreen(); * ``` * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @return {Player} self * @method requestFullscreen */ Player.prototype.requestFullscreen = function requestFullscreen() { var fsApi = _FullscreenApi2['default']; this.isFullscreen(true); if (fsApi.requestFullscreen) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when canceling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events Events.on(_document2['default'], fsApi.fullscreenchange, Fn.bind(this, function documentFullscreenChange(e) { this.isFullscreen(_document2['default'][fsApi.fullscreenElement]); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { Events.off(_document2['default'], fsApi.fullscreenchange, documentFullscreenChange); } this.trigger('fullscreenchange'); })); this.el_[fsApi.requestFullscreen](); } else if (this.tech.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Return the video to its normal size after having been in full screen mode * ```js * myPlayer.exitFullscreen(); * ``` * * @return {Player} self * @method exitFullscreen */ Player.prototype.exitFullscreen = function exitFullscreen() { var fsApi = _FullscreenApi2['default']; this.isFullscreen(false); // Check for browser element fullscreen support if (fsApi.requestFullscreen) { _document2['default'][fsApi.exitFullscreen](); } else if (this.tech.supportsFullScreen()) { this.techCall('exitFullScreen'); } else { this.exitFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us. * * @method enterFullWindow */ Player.prototype.enterFullWindow = function enterFullWindow() { this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = _document2['default'].documentElement.style.overflow; // Add listener for esc key to exit fullscreen Events.on(_document2['default'], 'keydown', Fn.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars _document2['default'].documentElement.style.overflow = 'hidden'; // Apply fullscreen styles Dom.addElClass(_document2['default'].body, 'vjs-full-window'); this.trigger('enterFullWindow'); }; /** * Check for call to either exit full window or full screen on ESC key * * @param {String} event Event to check for key press * @method fullWindowOnEscKey */ Player.prototype.fullWindowOnEscKey = function fullWindowOnEscKey(event) { if (event.keyCode === 27) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } }; /** * Exit full window * * @method exitFullWindow */ Player.prototype.exitFullWindow = function exitFullWindow() { this.isFullWindow = false; Events.off(_document2['default'], 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. _document2['default'].documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles Dom.removeElClass(_document2['default'].body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); this.trigger('exitFullWindow'); }; /** * Select source based on tech order * * @param {Array} sources The sources for a media asset * @return {Object|Boolean} Object of source and tech order, otherwise false * @method selectSource */ Player.prototype.selectSource = function selectSource(sources) { // Loop through each playback technology in the options order for (var i = 0, j = this.options_.techOrder; i < j.length; i++) { var techName = _toTitleCase2['default'](j[i]); var tech = _Component3['default'].getComponent(techName); // Check if the current tech is defined before continuing if (!tech) { _log2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); continue; } // Check if the browser supports this technology if (tech.isSupported()) { // Loop through each source object for (var a = 0, b = sources; a < b.length; a++) { var source = b[a]; // Check if source can be played with this technology if (tech.canPlaySource(source)) { return { source: source, tech: techName }; } } } } return false; }; /** * The source function updates the video source * There are three types of variables you can pass as the argument. * **URL String**: A URL to the the video file. Use this method if you are sure * the current playback technology (HTML5/Flash) can support the source you * provide. Currently only MP4 files can be used in both HTML5 and Flash. * ```js * myPlayer.src("http://www.example.com/path/to/video.mp4"); * ``` * **Source Object (or element):* * A javascript object containing information * about the source file. Use this method if you want the player to determine if * it can support the file using the type information. * ```js * myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); * ``` * **Array of Source Objects:* * To provide multiple versions of the source so * that it can be played using HTML5 across browsers you can use an array of * source objects. Video.js will detect which version is supported and load that * file. * ```js * myPlayer.src([ * { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }, * { type: "video/webm", src: "http://www.example.com/path/to/video.webm" }, * { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" } * ]); * ``` * * @param {String|Object|Array=} source The source URL, object, or array of sources * @return {String} The current video source when getting * @return {String} The player when setting * @method src */ Player.prototype.src = function src(source) { if (source === undefined) { return this.techGet('src'); } var currentTech = _Component3['default'].getComponent(this.techName); // case: Array of source objects to choose from and pick the best to play if (Array.isArray(source)) { this.sourceList_(source); // case: URL String (http://myvideo...) } else if (typeof source === 'string') { // create a source object from the string this.src({ src: source }); // case: Source object { src: '', type: '' ... } } else if (source instanceof Object) { // check if the source has a type and the loaded tech cannot play the source // if there's no type we'll just try the current tech if (source.type && !currentTech.canPlaySource(source)) { // create a source list with the current source and send through // the tech loop to check for a compatible technology this.sourceList_([source]); } else { this.cache_.src = source.src; this.currentType_ = source.type || ''; // wait until the tech is ready to set the source this.ready(function () { // The setSource tech method was added with source handlers // so older techs won't support it // We need to check the direct prototype for the case where subclasses // of the tech do not support source handlers if (currentTech.prototype.hasOwnProperty('setSource')) { this.techCall('setSource', source); } else { this.techCall('src', source.src); } if (this.options_.preload === 'auto') { this.load(); } if (this.options_.autoplay) { this.play(); } }); } } return this; }; /** * Handle an array of source objects * * @param {Array} sources Array of source objects * @private * @method sourceList_ */ Player.prototype.sourceList_ = function sourceList_(sources) { var sourceTech = this.selectSource(sources); if (sourceTech) { if (sourceTech.tech === this.techName) { // if this technology is already loaded, set the source this.src(sourceTech.source); } else { // load this technology with the chosen source this.loadTech(sourceTech.tech, sourceTech.source); } } else { // We need to wrap this in a timeout to give folks a chance to add error event handlers this.setTimeout(function () { this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it // this needs a better comment about why this is needed this.triggerReady(); } }; /** * Begin loading the src data. * * @return {Player} Returns the player * @method load */ Player.prototype.load = function load() { this.techCall('load'); return this; }; /** * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 * Can be used in conjuction with `currentType` to assist in rebuilding the current source object. * * @return {String} The current source * @method currentSrc */ Player.prototype.currentSrc = function currentSrc() { return this.techGet('currentSrc') || this.cache_.src || ''; }; /** * Get the current source type e.g. video/mp4 * This can allow you rebuild the current source object so that you could load the same * source and tech later * * @return {String} The source MIME type * @method currentType */ Player.prototype.currentType = function currentType() { return this.currentType_ || ''; }; /** * Get or set the preload attribute * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The preload attribute value when getting * @return {Player} Returns the player when setting * @method preload */ Player.prototype.preload = function preload(value) { if (value !== undefined) { this.techCall('setPreload', value); this.options_.preload = value; return this; } return this.techGet('preload'); }; /** * Get or set the autoplay attribute. * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The autoplay attribute value when getting * @return {Player} Returns the player when setting * @method autoplay */ Player.prototype.autoplay = function autoplay(value) { if (value !== undefined) { this.techCall('setAutoplay', value); this.options_.autoplay = value; return this; } return this.techGet('autoplay', value); }; /** * Get or set the loop attribute on the video element. * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The loop attribute value when getting * @return {Player} Returns the player when setting * @method loop */ Player.prototype.loop = function loop(value) { if (value !== undefined) { this.techCall('setLoop', value); this.options_.loop = value; return this; } return this.techGet('loop'); }; /** * get or set the poster image source url * ##### EXAMPLE: * ```js * // get * var currentPoster = myPlayer.poster(); * // set * myPlayer.poster('http://example.com/myImage.jpg'); * ``` * * @param {String=} src Poster image source URL * @return {String} poster URL when getting * @return {Player} self when setting * @method poster */ Player.prototype.poster = function poster(src) { if (src === undefined) { return this.poster_; } // The correct way to remove a poster is to set as an empty string // other falsey values will throw errors if (!src) { src = ''; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall('setPoster', src); // alert components that the poster has been set this.trigger('posterchange'); return this; }; /** * Get or set whether or not the controls are showing. * * @param {Boolean} bool Set controls to showing or not * @return {Boolean} Controls are showing * @method controls */ Player.prototype.controls = function controls(bool) { if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.controls_ !== bool) { this.controls_ = bool; if (this.usingNativeControls()) { this.techCall('setControls', bool); } if (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); this.trigger('controlsenabled'); if (!this.usingNativeControls()) { this.addTechControlsListeners(); } } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); this.trigger('controlsdisabled'); if (!this.usingNativeControls()) { this.removeTechControlsListeners(); } } } return this; } return !!this.controls_; }; /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @param {Boolean} bool True signals that native controls are on * @return {Player} Returns the player * @private * @method usingNativeControls */ Player.prototype.usingNativeControls = function usingNativeControls(bool) { if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ !== bool) { this.usingNativeControls_ = bool; if (bool) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event usingnativecontrols * @memberof Player * @instance * @private */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event usingcustomcontrols * @memberof Player * @instance * @private */ this.trigger('usingcustomcontrols'); } } return this; } return !!this.usingNativeControls_; }; /** * Set or get the current MediaError * * @param {*} err A MediaError or a String/Number to be turned into a MediaError * @return {MediaError|null} when getting * @return {Player} when setting * @method error */ Player.prototype.error = function error(err) { if (err === undefined) { return this.error_ || null; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); return this; } // error instance if (err instanceof _MediaError2['default']) { this.error_ = err; } else { this.error_ = new _MediaError2['default'](err); } // fire an error event on the player this.trigger('error'); // add the vjs-error classname to the player this.addClass('vjs-error'); // log the name of the error type and any message // ie8 just logs "[object object]" if you just log the error object _log2['default'].error('(CODE:' + this.error_.code + ' ' + _MediaError2['default'].errorTypes[this.error_.code] + ')', this.error_.message, this.error_); return this; }; /** * Returns whether or not the player is in the "ended" state. * * @return {Boolean} True if the player is in the ended state, false if not. * @method ended */ Player.prototype.ended = function ended() { return this.techGet('ended'); }; /** * Returns whether or not the player is in the "seeking" state. * * @return {Boolean} True if the player is in the seeking state, false if not. * @method seeking */ Player.prototype.seeking = function seeking() { return this.techGet('seeking'); }; /** * Returns the TimeRanges of the media that are currently available * for seeking to. * * @return {TimeRanges} the seekable intervals of the media timeline * @method seekable */ Player.prototype.seekable = function seekable() { return this.techGet('seekable'); }; /** * Report user activity * * @param {Object} event Event object * @method reportUserActivity */ Player.prototype.reportUserActivity = function reportUserActivity(event) { this.userActivity_ = true; }; /** * Get/set if user is active * * @param {Boolean} bool Value when setting * @return {Boolean} Value if user is active user when getting * @method userActive */ Player.prototype.userActive = function userActive(bool) { if (bool !== undefined) { bool = !!bool; if (bool !== this.userActive_) { this.userActive_ = bool; if (bool) { // If the user was inactive and is now active we want to reset the // inactivity timer this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); this.trigger('useractive'); } else { // We're switching the state to inactive manually, so erase any other // activity this.userActivity_ = false; // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 if (this.tech) { this.tech.one('mousemove', function (e) { e.stopPropagation(); e.preventDefault(); }); } this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); this.trigger('userinactive'); } } return this; } return this.userActive_; }; /** * Listen for user activity based on timeout value * * @method listenForUserActivity */ Player.prototype.listenForUserActivity = function listenForUserActivity() { var mouseInProgress = undefined, lastMoveX = undefined, lastMoveY = undefined; var handleActivity = Fn.bind(this, this.reportUserActivity); var handleMouseMove = function handleMouseMove(e) { // #1068 - Prevent mousemove spamming // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970 if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) { lastMoveX = e.screenX; lastMoveY = e.screenY; handleActivity(); } }; var handleMouseDown = function handleMouseDown() { handleActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = this.setInterval(handleActivity, 250); }; var handleMouseUp = function handleMouseUp(event) { handleActivity(); // Stop the interval that maintains activity if the mouse/touch is down this.clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', handleMouseDown); this.on('mousemove', handleMouseMove); this.on('mouseup', handleMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', handleActivity); this.on('keyup', handleActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ var inactivityTimeout = undefined; var activityCheck = this.setInterval(function () { // Check to see if mouse/touch activity has happened if (this.userActivity_) { // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over this.clearTimeout(inactivityTimeout); var timeout = this.options_.inactivityTimeout; if (timeout > 0) { // In <timeout> milliseconds, if no more activity has occurred the // user will be considered inactive inactivityTimeout = this.setTimeout(function () { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activityCheck loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }, timeout); } } }, 250); }; /** * Gets or sets the current playback rate. A playback rate of * 1.0 represents normal speed and 0.5 would indicate half-speed * playback, for instance. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate * * @param {Number} rate New playback rate to set. * @return {Number} Returns the new playback rate when setting * @return {Number} Returns the current playback rate when getting * @method playbackRate */ Player.prototype.playbackRate = function playbackRate(rate) { if (rate !== undefined) { this.techCall('setPlaybackRate', rate); return this; } if (this.tech && this.tech.featuresPlaybackRate) { return this.techGet('playbackRate'); } else { return 1; } }; /** * Gets or sets the audio flag * * @param {Boolean} bool True signals that this is an audio player. * @return {Boolean} Returns true if player is audio, false if not when getting * @return {Player} Returns the player if setting * @private * @method isAudio */ Player.prototype.isAudio = function isAudio(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return this; } return !!this.isAudio_; }; /** * Returns the current state of network activity for the element, from * the codes in the list below. * - NETWORK_EMPTY (numeric value 0) * The element has not yet been initialised. All attributes are in * their initial states. * - NETWORK_IDLE (numeric value 1) * The element's resource selection algorithm is active and has * selected a resource, but it is not actually using the network at * this time. * - NETWORK_LOADING (numeric value 2) * The user agent is actively trying to download data. * - NETWORK_NO_SOURCE (numeric value 3) * The element's resource selection algorithm is active, but it has * not yet found a resource to use. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states * @return {Number} the current network activity state * @method networkState */ Player.prototype.networkState = function networkState() { return this.techGet('networkState'); }; /** * Returns a value that expresses the current state of the element * with respect to rendering the current playback position, from the * codes in the list below. * - HAVE_NOTHING (numeric value 0) * No information regarding the media resource is available. * - HAVE_METADATA (numeric value 1) * Enough of the resource has been obtained that the duration of the * resource is available. * - HAVE_CURRENT_DATA (numeric value 2) * Data for the immediate current playback position is available. * - HAVE_FUTURE_DATA (numeric value 3) * Data for the immediate current playback position is available, as * well as enough data for the user agent to advance the current * playback position in the direction of playback. * - HAVE_ENOUGH_DATA (numeric value 4) * The user agent estimates that enough data is available for * playback to proceed uninterrupted. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate * @return {Number} the current playback rendering state * @method readyState */ Player.prototype.readyState = function readyState() { return this.techGet('readyState'); }; /* * Text tracks are tracks of timed text events. * Captions - text displayed over the video for the hearing impaired * Subtitles - text displayed over the video for those who don't understand language in the video * Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video * Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device */ /** * Get an array of associated text tracks. captions, subtitles, chapters, descriptions * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * * @return {Array} Array of track objects * @method textTracks */ Player.prototype.textTracks = function textTracks() { // cannot use techGet directly because it checks to see whether the tech is ready. // Flash is unlikely to be ready in time but textTracks should still work. return this.tech && this.tech.textTracks(); }; /** * Get an array of remote text tracks * * @return {Array} * @method remoteTextTracks */ Player.prototype.remoteTextTracks = function remoteTextTracks() { return this.tech && this.tech.remoteTextTracks(); }; /** * Add a text track * In addition to the W3C settings we allow adding additional info through options. * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * * @param {String} kind Captions, subtitles, chapters, descriptions, or metadata * @param {String=} label Optional label * @param {String=} language Optional language * @method addTextTrack */ Player.prototype.addTextTrack = function addTextTrack(kind, label, language) { return this.tech && this.tech.addTextTrack(kind, label, language); }; /** * Add a remote text track * * @param {Object} options Options for remote text track * @method addRemoteTextTrack */ Player.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) { return this.tech && this.tech.addRemoteTextTrack(options); }; /** * Remove a remote text track * * @param {Object} track Remote text track to remove * @method removeRemoteTextTrack */ Player.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { this.tech && this.tech.removeRemoteTextTrack(track); }; /** * Get video width * * @return {Number} Video width * @method videoWidth */ Player.prototype.videoWidth = function videoWidth() { return this.tech && this.tech.videoWidth && this.tech.videoWidth() || 0; }; /** * Get video height * * @return {Number} Video height * @method videoHeight */ Player.prototype.videoHeight = function videoHeight() { return this.tech && this.tech.videoHeight && this.tech.videoHeight() || 0; }; // Methods to add support for // initialTime: function(){ return this.techCall('initialTime'); }, // startOffsetTime: function(){ return this.techCall('startOffsetTime'); }, // played: function(){ return this.techCall('played'); }, // seekable: function(){ return this.techCall('seekable'); }, // videoTracks: function(){ return this.techCall('videoTracks'); }, // audioTracks: function(){ return this.techCall('audioTracks'); }, // defaultPlaybackRate: function(){ return this.techCall('defaultPlaybackRate'); }, // mediaGroup: function(){ return this.techCall('mediaGroup'); }, // controller: function(){ return this.techCall('controller'); }, // defaultMuted: function(){ return this.techCall('defaultMuted'); } // TODO // currentSrcList: the array of sources including other formats and bitrates // playList: array of source lists in order of playback /** * The player's language code * NOTE: The language should be set in the player options if you want the * the controls to be built with a specific language. Changing the lanugage * later will not update controls text. * * @param {String} code The locale string * @return {String} The locale string when getting * @return {Player} self when setting * @method language */ Player.prototype.language = function language(code) { if (code === undefined) { return this.language_; } this.language_ = ('' + code).toLowerCase(); return this; }; /** * Get the player's language dictionary * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time * Languages specified directly in the player options have precedence * * @return {Array} Array of languages * @method languages */ Player.prototype.languages = function languages() { return _mergeOptions2['default'](_globalOptions2['default'].languages, this.languages_); }; /** * Converts track info to JSON * * @return {Object} JSON object of options * @method toJSON */ Player.prototype.toJSON = function toJSON() { var options = _mergeOptions2['default'](this.options_); var tracks = options.tracks; options.tracks = []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // deep merge tracks and null out player so no circular references track = _mergeOptions2['default'](track); track.player = undefined; options.tracks[i] = track; } return options; }; /** * Gets tag settings * * @param {Element} tag The player tag * @return {Array} An array of sources and track objects * @static * @method getTagSettings */ Player.getTagSettings = function getTagSettings(tag) { var baseOptions = { sources: [], tracks: [] }; var tagOptions = Dom.getElAttributes(tag); var dataSetup = tagOptions['data-setup']; // Check if data-setup attr exists. if (dataSetup !== null) { // Parse options JSON // If empty string, make it a parsable json object. var _safeParseTuple = _safeParseTuple3['default'](dataSetup || '{}'); var err = _safeParseTuple[0]; var data = _safeParseTuple[1]; if (err) { _log2['default'].error(err); } _assign2['default'](tagOptions, data); } _assign2['default'](baseOptions, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children = tag.childNodes; for (var i = 0, j = children.length; i < j; i++) { var child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ var childName = child.nodeName.toLowerCase(); if (childName === 'source') { baseOptions.sources.push(Dom.getElAttributes(child)); } else if (childName === 'track') { baseOptions.tracks.push(Dom.getElAttributes(child)); } } } return baseOptions; }; return Player; })(_Component3['default']); /* * Global player list * * @type {Object} */ Player.players = {}; /* * Player instance options, surfaced using options * options = Player.prototype.options_ * Make changes in options, not here. * All options should use string keys so they avoid * renaming by closure compiler * * @type {Object} * @private */ Player.prototype.options_ = _globalOptions2['default']; /** * Fired when the player has initial duration and dimension information * * @event loadedmetadata */ Player.prototype.handleLoadedMetaData; /** * Fired when the player has downloaded data at the current playback position * * @event loadeddata */ Player.prototype.handleLoadedData; /** * Fired when the player has finished downloading the source data * * @event loadedalldata */ Player.prototype.handleLoadedAllData; /** * Fired when the user is active, e.g. moves the mouse over the player * * @event useractive */ Player.prototype.handleUserActive; /** * Fired when the user is inactive, e.g. a short delay after the last mouse move or control interaction * * @event userinactive */ Player.prototype.handleUserInactive; /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depending on the * playback technology in use. * * @event timeupdate */ Player.prototype.handleTimeUpdate; /** * Fired when the volume changes * * @event volumechange */ Player.prototype.handleVolumeChange; /** * Fired when an error occurs * * @event error */ Player.prototype.handleError; Player.prototype.flexNotSupported_ = function () { var elem = _document2['default'].createElement('i'); // Note: We don't actually use flexBasis (or flexOrder), but it's one of the more // common flex features that we can rely on when checking for flex support. return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || 'msFlexOrder' in elem.style /* IE10-specific (2012 flex spec) */); }; _Component3['default'].registerComponent('Player', Player); exports['default'] = Player; module.exports = exports['default']; },{"./big-play-button.js":50,"./component.js":52,"./control-bar/control-bar.js":53,"./error-display.js":82,"./fullscreen-api.js":85,"./global-options.js":86,"./loading-spinner.js":87,"./media-error.js":88,"./poster-image.js":94,"./tech/html5.js":99,"./tech/loader.js":100,"./tracks/text-track-display.js":103,"./tracks/text-track-settings.js":106,"./utils/browser.js":108,"./utils/buffer.js":109,"./utils/dom.js":111,"./utils/events.js":112,"./utils/fn.js":113,"./utils/guid.js":115,"./utils/log.js":116,"./utils/merge-options.js":117,"./utils/time-ranges.js":118,"./utils/to-title-case.js":119,"global/document":1,"global/window":2,"object.assign":44,"safe-json-parse/tuple":49}],93:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file plugins.js */ var _Player = _dereq_('./player.js'); var _Player2 = _interopRequireWildcard(_Player); /** * The method for registering a video.js plugin * * @param {String} name The name of the plugin * @param {Function} init The function that is run when the player inits * @method plugin */ var plugin = function plugin(name, init) { _Player2['default'].prototype[name] = init; }; exports['default'] = plugin; module.exports = exports['default']; },{"./player.js":92}],94:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file poster-image.js */ var _Button2 = _dereq_('./button.js'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('./component.js'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _import2 = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_import2); var _import3 = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_import3); /** * The component that handles showing the poster image. * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class PosterImage */ var PosterImage = (function (_Button) { function PosterImage(player, options) { _classCallCheck(this, PosterImage); _Button.call(this, player, options); this.update(); player.on('posterchange', Fn.bind(this, this.update)); } _inherits(PosterImage, _Button); /** * Clean up the poster image * * @method dispose */ PosterImage.prototype.dispose = function dispose() { this.player().off('posterchange', this.update); _Button.prototype.dispose.call(this); }; /** * Create the poster's image element * * @return {Element} * @method createEl */ PosterImage.prototype.createEl = function createEl() { var el = Dom.createEl('div', { className: 'vjs-poster', // Don't want poster to be tabbable. tabIndex: -1 }); // To ensure the poster image resizes while maintaining its original aspect // ratio, use a div with `background-size` when available. For browsers that // do not support `background-size` (e.g. IE8), fall back on using a regular // img element. if (!browser.BACKGROUND_SIZE_SUPPORTED) { this.fallbackImg_ = Dom.createEl('img'); el.appendChild(this.fallbackImg_); } return el; }; /** * Event handler for updates to the player's poster source * * @method update */ PosterImage.prototype.update = function update() { var url = this.player().poster(); this.setSrc(url); // If there's no poster source we should display:none on this component // so it's not still clickable or right-clickable if (url) { this.show(); } else { this.hide(); } }; /** * Set the poster source depending on the display method * * @param {String} url The URL to the poster source * @method setSrc */ PosterImage.prototype.setSrc = function setSrc(url) { if (this.fallbackImg_) { this.fallbackImg_.src = url; } else { var backgroundImage = ''; // Any falsey values should stay as an empty string, otherwise // this will throw an extra error if (url) { backgroundImage = 'url("' + url + '")'; } this.el_.style.backgroundImage = backgroundImage; } }; /** * Event handler for clicks on the poster image * * @method handleClick */ PosterImage.prototype.handleClick = function handleClick() { // We don't want a click to trigger playback when controls are disabled // but CSS should be hiding the poster to prevent that from happening if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; return PosterImage; })(_Button3['default']); _Component2['default'].registerComponent('PosterImage', PosterImage); exports['default'] = PosterImage; module.exports = exports['default']; },{"./button.js":51,"./component.js":52,"./utils/browser.js":108,"./utils/dom.js":111,"./utils/fn.js":113}],95:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file setup.js * * Functions for automatically setting up a player * based on the data-setup attribute of the video tag */ var _import = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_import); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _windowLoaded = false; var videojs = undefined; // Automatically set up any tags that have a data-setup attribute var autoSetup = function autoSetup() { // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop through each list of elements // to build up a new, combined list of elements. var vids = _document2['default'].getElementsByTagName('video'); var audios = _document2['default'].getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for (var i = 0, e = vids.length; i < e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for (var i = 0, e = audios.length; i < e; i++) { mediaEls.push(audios[i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (var i = 0, e = mediaEls.length; i < e; i++) { var mediaEl = mediaEls[i]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl.player === undefined) { var options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. var player = videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!_windowLoaded) { autoSetupTimeout(1); } }; // Pause to let the DOM keep processing var autoSetupTimeout = function autoSetupTimeout(wait, vjs) { videojs = vjs; setTimeout(autoSetup, wait); }; if (_document2['default'].readyState === 'complete') { _windowLoaded = true; } else { Events.one(_window2['default'], 'load', function () { _windowLoaded = true; }); } var hasLoaded = function hasLoaded() { return _windowLoaded; }; exports.autoSetup = autoSetup; exports.autoSetupTimeout = autoSetupTimeout; exports.hasLoaded = hasLoaded; },{"./utils/events.js":112,"global/document":1,"global/window":2}],96:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file slider.js */ var _Component2 = _dereq_('../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); /** * The base functionality for sliders like the volume bar and seek bar * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class Slider */ var Slider = (function (_Component) { function Slider(player, options) { _classCallCheck(this, Slider); _Component.call(this, player, options); // Set property names to bar and handle to match with the child Slider class is looking for this.bar = this.getChild(this.options_.barName); this.handle = this.getChild(this.options_.handleName); // Set a horizontal or vertical class on the slider depending on the slider type this.vertical(!!this.options_.vertical); this.on('mousedown', this.handleMouseDown); this.on('touchstart', this.handleMouseDown); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); this.on('click', this.handleClick); this.on(player, 'controlsvisible', this.update); this.on(player, this.playerEvent, this.update); } _inherits(Slider, _Component); /** * Create the component's DOM element * * @param {String} type Type of element to create * @param {Object=} props List of properties in Object form * @return {Element} * @method createEl */ Slider.prototype.createEl = function createEl(type) { var props = arguments[1] === undefined ? {} : arguments[1]; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = _assign2['default']({ role: 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, tabIndex: 0 }, props); return _Component.prototype.createEl.call(this, type, props); }; /** * Handle mouse down on slider * * @param {Object} event Mouse down event object * @method handleMouseDown */ Slider.prototype.handleMouseDown = function handleMouseDown(event) { event.preventDefault(); Dom.blockTextSelection(); this.addClass('vjs-sliding'); this.on(_document2['default'], 'mousemove', this.handleMouseMove); this.on(_document2['default'], 'mouseup', this.handleMouseUp); this.on(_document2['default'], 'touchmove', this.handleMouseMove); this.on(_document2['default'], 'touchend', this.handleMouseUp); this.handleMouseMove(event); }; /** * To be overridden by a subclass * * @method handleMouseMove */ Slider.prototype.handleMouseMove = function handleMouseMove() {}; /** * Handle mouse up on Slider * * @method handleMouseUp */ Slider.prototype.handleMouseUp = function handleMouseUp() { Dom.unblockTextSelection(); this.removeClass('vjs-sliding'); this.off(_document2['default'], 'mousemove', this.handleMouseMove); this.off(_document2['default'], 'mouseup', this.handleMouseUp); this.off(_document2['default'], 'touchmove', this.handleMouseMove); this.off(_document2['default'], 'touchend', this.handleMouseUp); this.update(); }; /** * Update slider * * @method update */ Slider.prototype.update = function update() { // In VolumeBar init we have a setTimeout for update that pops and update to the end of the // execution stack. The player is destroyed before then update will cause an error if (!this.el_) { return; } // If scrubbing, we could use a cached value to make the handle keep up with the user's mouse. // On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration(); var progress = this.getPercent(); var bar = this.bar; // If there's no bar... if (!bar) { return; } // Protect against no duration and other division issues if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) { progress = 0; } // Convert to a percentage for setting var percentage = (progress * 100).toFixed(2) + '%'; // Set the new bar width or height if (this.vertical()) { bar.el().style.height = percentage; } else { bar.el().style.width = percentage; } }; /** * Calculate distance for slider * * @param {Object} event Event object * @method calculateDistance */ Slider.prototype.calculateDistance = function calculateDistance(event) { var el = this.el_; var box = Dom.findElPosition(el); var boxW = el.offsetWidth; var boxH = el.offsetHeight; var handle = this.handle; if (this.options_.vertical) { var boxY = box.top; var pageY = undefined; if (event.changedTouches) { pageY = event.changedTouches[0].pageY; } else { pageY = event.pageY; } if (handle) { var handleH = handle.el().offsetHeight; // Adjusted X and Width, so handle doesn't go outside the bar boxY = boxY + handleH / 2; boxH = boxH - handleH; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH)); } else { var boxX = box.left; var pageX = undefined; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; } else { pageX = event.pageX; } if (handle) { var handleW = handle.el().offsetWidth; // Adjusted X and Width, so handle doesn't go outside the bar boxX = boxX + handleW / 2; boxW = boxW - handleW; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, (pageX - boxX) / boxW)); } }; /** * Handle on focus for slider * * @method handleFocus */ Slider.prototype.handleFocus = function handleFocus() { this.on(_document2['default'], 'keydown', this.handleKeyPress); }; /** * Handle key press for slider * * @param {Object} event Event object * @method handleKeyPress */ Slider.prototype.handleKeyPress = function handleKeyPress(event) { if (event.which === 37 || event.which === 40) { // Left and Down Arrows event.preventDefault(); this.stepBack(); } else if (event.which === 38 || event.which === 39) { // Up and Right Arrows event.preventDefault(); this.stepForward(); } }; /** * Handle on blur for slider * * @method handleBlur */ Slider.prototype.handleBlur = function handleBlur() { this.off(_document2['default'], 'keydown', this.handleKeyPress); }; /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * * @param {Object} event Event object * @method handleClick */ Slider.prototype.handleClick = function handleClick(event) { event.stopImmediatePropagation(); event.preventDefault(); }; /** * Get/set if slider is horizontal for vertical * * @param {Boolean} bool True if slider is vertical, false is horizontal * @return {Boolean} True if slider is vertical, false is horizontal * @method vertical */ Slider.prototype.vertical = function vertical(bool) { if (bool === undefined) { return this.vertical_ || false; } this.vertical_ = !!bool; if (this.vertical_) { this.addClass('vjs-slider-vertical'); } else { this.addClass('vjs-slider-horizontal'); } return this; }; return Slider; })(_Component3['default']); _Component3['default'].registerComponent('Slider', Slider); exports['default'] = Slider; module.exports = exports['default']; },{"../component.js":52,"../utils/dom.js":111,"global/document":1,"object.assign":44}],97:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file flash-rtmp.js */ function FlashRtmpDecorator(Flash) { Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; Flash.streamFromParts = function (connection, stream) { return connection + '&' + stream; }; Flash.streamToParts = function (src) { var parts = { connection: '', stream: '' }; if (!src) return parts; // Look for the normal URL separator we expect, '&'. // If found, we split the URL into two pieces around the // first '&'. var connEnd = src.indexOf('&'); var streamBegin = undefined; if (connEnd !== -1) { streamBegin = connEnd + 1; } else { // If there's not a '&', we use the last '/' as the delimiter. connEnd = streamBegin = src.lastIndexOf('/') + 1; if (connEnd === 0) { // really, there's not a '/'? connEnd = streamBegin = src.length; } } parts.connection = src.substring(0, connEnd); parts.stream = src.substring(streamBegin, src.length); return parts; }; Flash.isStreamingType = function (srcType) { return srcType in Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid Flash.RTMP_RE = /^rtmp[set]?:\/\//i; Flash.isStreamingSrc = function (src) { return Flash.RTMP_RE.test(src); }; /** * A source handler for RTMP urls * @type {Object} */ Flash.rtmpSourceHandler = {}; /** * Check Flash can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.rtmpSourceHandler.canHandleSource = function (source) { if (Flash.isStreamingType(source.type) || Flash.isStreamingSrc(source.src)) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.rtmpSourceHandler.handleSource = function (source, tech) { var srcParts = Flash.streamToParts(source.src); tech.setRtmpConnection(srcParts.connection); tech.setRtmpStream(srcParts.stream); }; // Register the native source handler Flash.registerSourceHandler(Flash.rtmpSourceHandler); return Flash; } exports['default'] = FlashRtmpDecorator; module.exports = exports['default']; },{}],98:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file flash.js * VideoJS-SWF - Custom Flash Player with HTML5-ish API * https://github.com/zencoder/video-js-swf * Not using setupTriggers. Using global onEvent func to distribute events */ var _Tech2 = _dereq_('./tech'); var _Tech3 = _interopRequireWildcard(_Tech2); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/url.js'); var Url = _interopRequireWildcard(_import2); var _createTimeRange = _dereq_('../utils/time-ranges.js'); var _FlashRtmpDecorator = _dereq_('./flash-rtmp'); var _FlashRtmpDecorator2 = _interopRequireWildcard(_FlashRtmpDecorator); var _Component = _dereq_('../component'); var _Component2 = _interopRequireWildcard(_Component); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); var navigator = _window2['default'].navigator; /** * Flash Media Controller - Wrapper for fallback SWF API * * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Tech * @class Flash */ var Flash = (function (_Tech) { function Flash(options, ready) { _classCallCheck(this, Flash); _Tech.call(this, options, ready); // If source was supplied pass as a flash var. if (options.source) { this.ready(function () { this.setSource(options.source); }); } // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // This allows resetting the playhead when we catch the reload if (options.startTime) { this.ready(function () { this.load(); this.play(); this.currentTime(options.startTime); }); } // Add global window functions that the swf expects // A 4.x workflow we weren't able to solve for in 5.0 // because of the need to hard code these functions // into the swf for security reasons _window2['default'].videojs = _window2['default'].videojs || {}; _window2['default'].videojs.Flash = _window2['default'].videojs.Flash || {}; _window2['default'].videojs.Flash.onReady = Flash.onReady; _window2['default'].videojs.Flash.onEvent = Flash.onEvent; _window2['default'].videojs.Flash.onError = Flash.onError; this.on('seeked', function () { this.lastSeekTarget_ = undefined; }); } _inherits(Flash, _Tech); /** * Create the component's DOM element * * @return {Element} * @method createEl */ Flash.prototype.createEl = function createEl() { var options = this.options_; // Generate ID for swf object var objId = options.techId; // Merge default flashvars with ones passed in to init var flashVars = _assign2['default']({ // SWF Callback Functions readyFunction: 'videojs.Flash.onReady', eventProxyFunction: 'videojs.Flash.onEvent', errorEventProxyFunction: 'videojs.Flash.onError', // Player Settings autoplay: options.autoplay, preload: options.preload, loop: options.loop, muted: options.muted }, options.flashVars); // Merge default parames with ones passed in var params = _assign2['default']({ wmode: 'opaque', // Opaque is needed to overlay controls, but can affect playback performance bgcolor: '#000000' // Using bgcolor prevents a white flash when the object is loading }, options.params); // Merge default attributes with ones passed in var attributes = _assign2['default']({ id: objId, name: objId, // Both ID and Name needed or swf to identify itself 'class': 'vjs-tech' }, options.attributes); this.el_ = Flash.embed(options.swf, flashVars, params, attributes); this.el_.tech = this; return this.el_; }; /** * Play for flash tech * * @method play */ Flash.prototype.play = function play() { this.el_.vjs_play(); }; /** * Pause for flash tech * * @method pause */ Flash.prototype.pause = function pause() { this.el_.vjs_pause(); }; /** * Get/set video * * @param {Object=} src Source object * @return {Object} * @method src */ Flash.prototype.src = (function (_src) { function src(_x) { return _src.apply(this, arguments); } src.toString = function () { return _src.toString(); }; return src; })(function (src) { if (src === undefined) { return this.currentSrc(); } // Setting src through `src` not `setSrc` will be deprecated return this.setSrc(src); }); /** * Set video * * @param {Object=} src Source object * @deprecated * @method setSrc */ Flash.prototype.setSrc = function setSrc(src) { // Make sure source URL is absolute. src = Url.getAbsoluteURL(src); this.el_.vjs_src(src); // Currently the SWF doesn't autoplay if you load a source later. // e.g. Load player w/ no source, wait 2s, set src. if (this.autoplay()) { var tech = this; this.setTimeout(function () { tech.play(); }, 0); } }; /** * Returns true if the tech is currently seeking. * @return {boolean} true if seeking */ Flash.prototype.seeking = function seeking() { return this.lastSeekTarget_ !== undefined; }; /** * Set current time * * @param {Number} time Current time of video * @method setCurrentTime */ Flash.prototype.setCurrentTime = function setCurrentTime(time) { var seekable = this.seekable(); if (seekable.length) { // clamp to the current seekable range time = time > seekable.start(0) ? time : seekable.start(0); time = time < seekable.end(seekable.length - 1) ? time : seekable.end(seekable.length - 1); this.lastSeekTarget_ = time; this.trigger('seeking'); this.el_.vjs_setProperty('currentTime', time); _Tech.prototype.setCurrentTime.call(this); } }; /** * Get current time * * @param {Number=} time Current time of video * @return {Number} Current time * @method currentTime */ Flash.prototype.currentTime = function currentTime(time) { // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return this.lastSeekTarget_ || 0; } return this.el_.vjs_getProperty('currentTime'); }; /** * Get current source * * @method currentSrc */ Flash.prototype.currentSrc = function currentSrc() { if (this.currentSource_) { return this.currentSource_.src; } else { return this.el_.vjs_getProperty('currentSrc'); } }; /** * Load media into player * * @method load */ Flash.prototype.load = function load() { this.el_.vjs_load(); }; /** * Get poster * * @method poster */ Flash.prototype.poster = function poster() { this.el_.vjs_getProperty('poster'); }; /** * Poster images are not handled by the Flash tech so make this a no-op * * @method setPoster */ Flash.prototype.setPoster = function setPoster() {}; /** * Determine if can seek in media * * @return {TimeRangeObject} * @method seekable */ Flash.prototype.seekable = function seekable() { var duration = this.duration(); if (duration === 0) { return _createTimeRange.createTimeRange(); } return _createTimeRange.createTimeRange(0, duration); }; /** * Get buffered time range * * @return {TimeRangeObject} * @method buffered */ Flash.prototype.buffered = function buffered() { return _createTimeRange.createTimeRange(0, this.el_.vjs_getProperty('buffered')); }; /** * Get fullscreen support - * Flash does not allow fullscreen through javascript * so always returns false * * @return {Boolean} false * @method supportsFullScreen */ Flash.prototype.supportsFullScreen = function supportsFullScreen() { return false; // Flash does not allow fullscreen through javascript }; /** * Request to enter fullscreen * Flash does not allow fullscreen through javascript * so always returns false * * @return {Boolean} false * @method enterFullScreen */ Flash.prototype.enterFullScreen = function enterFullScreen() { return false; }; return Flash; })(_Tech3['default']); // Create setters and getters for attributes var _api = Flash.prototype; var _readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','); var _readOnly = 'error,networkState,readyState,initialTime,duration,startOffsetTime,paused,ended,videoTracks,audioTracks,videoWidth,videoHeight'.split(','); function _createSetter(attr) { var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1); _api['set' + attrUpper] = function (val) { return this.el_.vjs_setProperty(attr, val); }; } function _createGetter(attr) { _api[attr] = function () { return this.el_.vjs_getProperty(attr); }; } // Create getter and setters for all read/write attributes for (var i = 0; i < _readWrite.length; i++) { _createGetter(_readWrite[i]); _createSetter(_readWrite[i]); } // Create getters for read-only attributes for (var i = 0; i < _readOnly.length; i++) { _createGetter(_readOnly[i]); } /* Flash Support Testing -------------------------------------------------------- */ Flash.isSupported = function () { return Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; // Add Source Handler pattern functions to this tech _Tech3['default'].withSourceHandlers(Flash); /* * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.nativeSourceHandler = {}; /* * Check Flash can handle the source natively * * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.nativeSourceHandler.canHandleSource = function (source) { var type; function guessMimeType(src) { var ext = Url.getFileExtension(src); if (ext) { return 'video/' + ext; } return ''; } if (!source.type) { type = guessMimeType(source.src); } else { // Strip code information from the type because we don't get that specific type = source.type.replace(/;.*/, '').toLowerCase(); } if (type in Flash.formats) { return 'maybe'; } return ''; }; /* * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.nativeSourceHandler.handleSource = function (source, tech) { tech.setSrc(source.src); }; /* * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ Flash.nativeSourceHandler.dispose = function () {}; // Register the native source handler Flash.registerSourceHandler(Flash.nativeSourceHandler); Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; Flash.onReady = function (currSwf) { var el = Dom.getEl(currSwf); var tech = el && el.tech; // if there is no el then the tech has been disposed // and the tech element was removed from the player div if (tech && tech.el()) { // check that the flash object is really ready Flash.checkReady(tech); } }; // The SWF isn't always ready when it says it is. Sometimes the API functions still need to be added to the object. // If it's not ready, we set a timeout to check again shortly. Flash.checkReady = function (tech) { // stop worrying if the tech has been disposed if (!tech.el()) { return; } // check if API property exists if (tech.el().vjs_getProperty) { // tell tech it's ready tech.triggerReady(); } else { // wait longer this.setTimeout(function () { Flash.checkReady(tech); }, 50); } }; // Trigger events from the swf on the player Flash.onEvent = function (swfID, eventName) { var tech = Dom.getEl(swfID).tech; tech.trigger(eventName); }; // Log errors from the swf Flash.onError = function (swfID, err) { var tech = Dom.getEl(swfID).tech; var msg = 'FLASH: ' + err; if (err === 'srcnotfound') { tech.trigger('error', { code: 4, message: msg }); // errors we haven't categorized into the media errors } else { tech.trigger('error', msg); } }; // Flash Version Check Flash.version = function () { var version = '0,0,0'; // IE try { version = new _window2['default'].ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch (e) { try { if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) { version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } } catch (err) {} } return version.split(','); }; // Flash embedding method. Only used in non-iframe mode Flash.embed = function (swf, flashVars, params, attributes) { var code = Flash.getEmbedCode(swf, flashVars, params, attributes); // Get element by embedding code and retrieving created element var obj = Dom.createEl('div', { innerHTML: code }).childNodes[0]; return obj; }; Flash.getEmbedCode = function (swf, flashVars, params, attributes) { var objTag = '<object type="application/x-shockwave-flash" '; var flashVarsString = ''; var paramsString = ''; var attrsString = ''; // Convert flash vars to string if (flashVars) { Object.getOwnPropertyNames(flashVars).forEach(function (key) { flashVarsString += '' + key + '=' + flashVars[key] + '&amp;'; }); } // Add swf, flashVars, and other default params params = _assign2['default']({ movie: swf, flashvars: flashVarsString, allowScriptAccess: 'always', // Required to talk to swf allowNetworking: 'all' // All should be default, but having security issues. }, params); // Create param tags string Object.getOwnPropertyNames(params).forEach(function (key) { paramsString += '<param name="' + key + '" value="' + params[key] + '" />'; }); attributes = _assign2['default']({ // Add swf to attributes (need both for IE and Others to work) data: swf, // Default to 100% width/height width: '100%', height: '100%' }, attributes); // Create Attributes string Object.getOwnPropertyNames(attributes).forEach(function (key) { attrsString += '' + key + '="' + attributes[key] + '" '; }); return '' + objTag + '' + attrsString + '>' + paramsString + '</object>'; }; // Run Flash through the RTMP decorator _FlashRtmpDecorator2['default'](Flash); _Component2['default'].registerComponent('Flash', Flash); exports['default'] = Flash; module.exports = exports['default']; },{"../component":52,"../utils/dom.js":111,"../utils/time-ranges.js":118,"../utils/url.js":120,"./flash-rtmp":97,"./tech":101,"global/window":2,"object.assign":44}],99:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file html5.js * HTML5 Media Controller - Wrapper for HTML5 Media API */ var _Tech2 = _dereq_('./tech.js'); var _Tech3 = _interopRequireWildcard(_Tech2); var _Component = _dereq_('../component'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/url.js'); var Url = _interopRequireWildcard(_import2); var _import3 = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import3); var _log = _dereq_('../utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _import4 = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_import4); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); var _mergeOptions = _dereq_('../utils/merge-options.js'); var _mergeOptions2 = _interopRequireWildcard(_mergeOptions); /** * HTML5 Media Controller - Wrapper for HTML5 Media API * * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Tech * @class Html5 */ var Html5 = (function (_Tech) { function Html5(options, ready) { _classCallCheck(this, Html5); _Tech.call(this, options, ready); var source = options.source; // Set the source if one is provided // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) { this.setSource(source); } if (this.el_.hasChildNodes()) { var nodes = this.el_.childNodes; var nodesLength = nodes.length; var removeNodes = []; while (nodesLength--) { var node = nodes[nodesLength]; var nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { if (!this.featuresNativeTextTracks) { // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks removeNodes.push(node); } else { this.remoteTextTracks().addTrack_(node.track); } } } for (var i = 0; i < removeNodes.length; i++) { this.el_.removeChild(removeNodes[i]); } } if (this.featuresNativeTextTracks) { this.on('loadstart', Fn.bind(this, this.hideCaptions)); } // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if (browser.TOUCH_ENABLED && options.nativeControlsForTouch === true) { this.trigger('usenativecontrols'); } this.triggerReady(); } _inherits(Html5, _Tech); /** * Dispose of html5 media element * * @method dispose */ Html5.prototype.dispose = function dispose() { Html5.disposeMediaElement(this.el_); _Tech.prototype.dispose.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Html5.prototype.createEl = function createEl() { var el = this.options_.tag; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. if (!el || this.movingMediaElementInDOM === false) { // If the original tag is still there, clone and remove it. if (el) { var clone = el.cloneNode(false); el.parentNode.insertBefore(clone, el); Html5.disposeMediaElement(el); el = clone; } else { el = _document2['default'].createElement('video'); // determine if native controls should be used var tagAttributes = this.options_.tag && Dom.getElAttributes(this.options_.tag); var attributes = _mergeOptions2['default']({}, tagAttributes); if (!browser.TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) { delete attributes.controls; } Dom.setElAttributes(el, _assign2['default'](attributes, { id: this.options_.techId, 'class': 'vjs-tech' })); } if (this.options_.tracks) { for (var i = 0; i < this.options_.tracks.length; i++) { var _track = this.options_.tracks[i]; var trackEl = _document2['default'].createElement('track'); trackEl.kind = _track.kind; trackEl.label = _track.label; trackEl.srclang = _track.srclang; trackEl.src = _track.src; if ('default' in _track) { trackEl.setAttribute('default', 'default'); } el.appendChild(trackEl); } } } // Update specific tag settings, in case they were overridden var settingsAttrs = ['autoplay', 'preload', 'loop', 'muted']; for (var i = settingsAttrs.length - 1; i >= 0; i--) { var attr = settingsAttrs[i]; var overwriteAttrs = {}; if (typeof this.options_[attr] !== 'undefined') { overwriteAttrs[attr] = this.options_[attr]; } Dom.setElAttributes(el, overwriteAttrs); } return el; // jenniisawesome = true; }; /** * Hide captions from text track * * @method hideCaptions */ Html5.prototype.hideCaptions = function hideCaptions() { var tracks = this.el_.querySelectorAll('track'); var i = tracks.length; var kinds = { captions: 1, subtitles: 1 }; while (i--) { var _track2 = tracks[i].track; if (_track2 && _track2.kind in kinds && !tracks[i]['default']) { _track2.mode = 'disabled'; } } }; /** * Play for html5 tech * * @method play */ Html5.prototype.play = function play() { this.el_.play(); }; /** * Pause for html5 tech * * @method pause */ Html5.prototype.pause = function pause() { this.el_.pause(); }; /** * Paused for html5 tech * * @return {Boolean} * @method paused */ Html5.prototype.paused = function paused() { return this.el_.paused; }; /** * Get current time * * @return {Number} * @method currentTime */ Html5.prototype.currentTime = function currentTime() { return this.el_.currentTime; }; /** * Set current time * * @param {Number} seconds Current time of video * @method setCurrentTime */ Html5.prototype.setCurrentTime = function setCurrentTime(seconds) { try { this.el_.currentTime = seconds; } catch (e) { _log2['default'](e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } }; /** * Get duration * * @return {Number} * @method duration */ Html5.prototype.duration = function duration() { return this.el_.duration || 0; }; /** * Get a TimeRange object that represents the intersection * of the time ranges for which the user agent has all * relevant media * * @return {TimeRangeObject} * @method buffered */ Html5.prototype.buffered = function buffered() { return this.el_.buffered; }; /** * Get volume level * * @return {Number} * @method volume */ Html5.prototype.volume = function volume() { return this.el_.volume; }; /** * Set volume level * * @param {Number} percentAsDecimal Volume percent as a decimal * @method setVolume */ Html5.prototype.setVolume = function setVolume(percentAsDecimal) { this.el_.volume = percentAsDecimal; }; /** * Get if muted * * @return {Boolean} * @method muted */ Html5.prototype.muted = function muted() { return this.el_.muted; }; /** * Set muted * * @param {Boolean} If player is to be muted or note * @method setMuted */ Html5.prototype.setMuted = function setMuted(muted) { this.el_.muted = muted; }; /** * Get player width * * @return {Number} * @method width */ Html5.prototype.width = function width() { return this.el_.offsetWidth; }; /** * Get player height * * @return {Number} * @method height */ Html5.prototype.height = function height() { return this.el_.offsetHeight; }; /** * Get if there is fullscreen support * * @return {Boolean} * @method supportsFullScreen */ Html5.prototype.supportsFullScreen = function supportsFullScreen() { if (typeof this.el_.webkitEnterFullScreen === 'function') { var userAgent = _window2['default'].navigator.userAgent; // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) { return true; } } return false; }; /** * Request to enter fullscreen * * @method enterFullScreen */ Html5.prototype.enterFullScreen = function enterFullScreen() { var video = this.el_; if ('webkitDisplayingFullscreen' in video) { this.one('webkitbeginfullscreen', function () { this.one('webkitendfullscreen', function () { this.trigger('fullscreenchange', { isFullscreen: false }); }); this.trigger('fullscreenchange', { isFullscreen: true }); }); } if (video.paused && video.networkState <= video.HAVE_METADATA) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get iOS ~6.1 devices into a play/pause loop this.setTimeout(function () { video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } }; /** * Request to exit fullscreen * * @method exitFullScreen */ Html5.prototype.exitFullScreen = function exitFullScreen() { this.el_.webkitExitFullScreen(); }; /** * Get/set video * * @param {Object=} src Source object * @return {Object} * @method src */ Html5.prototype.src = (function (_src) { function src(_x) { return _src.apply(this, arguments); } src.toString = function () { return _src.toString(); }; return src; })(function (src) { if (src === undefined) { return this.el_.src; } else { // Setting src through `src` instead of `setSrc` will be deprecated this.setSrc(src); } }); /** * Set video * * @param {Object} src Source object * @deprecated * @method setSrc */ Html5.prototype.setSrc = function setSrc(src) { this.el_.src = src; }; /** * Load media into player * * @method load */ Html5.prototype.load = function load() { this.el_.load(); }; /** * Get current source * * @return {Object} * @method currentSrc */ Html5.prototype.currentSrc = function currentSrc() { return this.el_.currentSrc; }; /** * Get poster * * @return {String} * @method poster */ Html5.prototype.poster = function poster() { return this.el_.poster; }; /** * Set poster * * @param {String} val URL to poster image * @method */ Html5.prototype.setPoster = function setPoster(val) { this.el_.poster = val; }; /** * Get preload attribute * * @return {String} * @method preload */ Html5.prototype.preload = function preload() { return this.el_.preload; }; /** * Set preload attribute * * @param {String} val Value for preload attribute * @method setPreload */ Html5.prototype.setPreload = function setPreload(val) { this.el_.preload = val; }; /** * Get autoplay attribute * * @return {String} * @method autoplay */ Html5.prototype.autoplay = function autoplay() { return this.el_.autoplay; }; /** * Set autoplay attribute * * @param {String} val Value for preload attribute * @method setAutoplay */ Html5.prototype.setAutoplay = function setAutoplay(val) { this.el_.autoplay = val; }; /** * Get controls attribute * * @return {String} * @method controls */ Html5.prototype.controls = function controls() { return this.el_.controls; }; /** * Set controls attribute * * @param {String} val Value for controls attribute * @method setControls */ Html5.prototype.setControls = function setControls(val) { this.el_.controls = !!val; }; /** * Get loop attribute * * @return {String} * @method loop */ Html5.prototype.loop = function loop() { return this.el_.loop; }; /** * Set loop attribute * * @param {String} val Value for loop attribute * @method setLoop */ Html5.prototype.setLoop = function setLoop(val) { this.el_.loop = val; }; /** * Get error value * * @return {String} * @method error */ Html5.prototype.error = function error() { return this.el_.error; }; /** * Get whether or not the player is in the "seeking" state * * @return {Boolean} * @method seeking */ Html5.prototype.seeking = function seeking() { return this.el_.seeking; }; /** * Get a TimeRanges object that represents the * ranges of the media resource to which it is possible * for the user agent to seek. * * @return {TimeRangeObject} * @method seekable */ Html5.prototype.seekable = function seekable() { return this.el_.seekable; }; /** * Get if video ended * * @return {Boolean} * @method ended */ Html5.prototype.ended = function ended() { return this.el_.ended; }; /** * Get the value of the muted content attribute * This attribute has no dynamic effect, it only * controls the default state of the element * * @return {Boolean} * @method defaultMuted */ Html5.prototype.defaultMuted = function defaultMuted() { return this.el_.defaultMuted; }; /** * Get desired speed at which the media resource is to play * * @return {Number} * @method playbackRate */ Html5.prototype.playbackRate = function playbackRate() { return this.el_.playbackRate; }; /** * Returns a TimeRanges object that represents the ranges of the * media resource that the user agent has played. * @return {TimeRangeObject} the range of points on the media * timeline that has been reached through normal playback * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-played */ Html5.prototype.played = function played() { return this.el_.played; }; /** * Set desired speed at which the media resource is to play * * @param {Number} val Speed at which the media resource is to play * @method setPlaybackRate */ Html5.prototype.setPlaybackRate = function setPlaybackRate(val) { this.el_.playbackRate = val; }; /** * Get the current state of network activity for the element, from * the list below * NETWORK_EMPTY (numeric value 0) * NETWORK_IDLE (numeric value 1) * NETWORK_LOADING (numeric value 2) * NETWORK_NO_SOURCE (numeric value 3) * * @return {Number} * @method networkState */ Html5.prototype.networkState = function networkState() { return this.el_.networkState; }; /** * Get a value that expresses the current state of the element * with respect to rendering the current playback position, from * the codes in the list below * HAVE_NOTHING (numeric value 0) * HAVE_METADATA (numeric value 1) * HAVE_CURRENT_DATA (numeric value 2) * HAVE_FUTURE_DATA (numeric value 3) * HAVE_ENOUGH_DATA (numeric value 4) * * @return {Number} * @method readyState */ Html5.prototype.readyState = function readyState() { return this.el_.readyState; }; /** * Get width of video * * @return {Number} * @method videoWidth */ Html5.prototype.videoWidth = function videoWidth() { return this.el_.videoWidth; }; /** * Get height of video * * @return {Number} * @method videoHeight */ Html5.prototype.videoHeight = function videoHeight() { return this.el_.videoHeight; }; /** * Get text tracks * * @return {TextTrackList} * @method textTracks */ Html5.prototype.textTracks = function textTracks() { if (!this.featuresNativeTextTracks) { return _Tech.prototype.textTracks.call(this); } return this.el_.textTracks; }; /** * Creates and returns a text track object * * @param {String} kind Text track kind (subtitles, captions, descriptions * chapters and metadata) * @param {String=} label Label to identify the text track * @param {String=} language Two letter language abbreviation * @return {TextTrackObject} * @method addTextTrack */ Html5.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!this.featuresNativeTextTracks) { return _Tech.prototype.addTextTrack.call(this, kind, label, language); } return this.el_.addTextTrack(kind, label, language); }; /** * Creates and returns a remote text track object * * @param {Object} options The object should contain values for * kind, language, label and src (location of the WebVTT file) * @return {TextTrackObject} * @method addRemoteTextTrack */ Html5.prototype.addRemoteTextTrack = function addRemoteTextTrack() { var options = arguments[0] === undefined ? {} : arguments[0]; if (!this.featuresNativeTextTracks) { return _Tech.prototype.addRemoteTextTrack.call(this, options); } var track = _document2['default'].createElement('track'); if (options.kind) { track.kind = options.kind; } if (options.label) { track.label = options.label; } if (options.language || options.srclang) { track.srclang = options.language || options.srclang; } if (options['default']) { track['default'] = options['default']; } if (options.id) { track.id = options.id; } if (options.src) { track.src = options.src; } this.el().appendChild(track); if (track.track.kind === 'metadata') { track.track.mode = 'hidden'; } else { track.track.mode = 'disabled'; } track.onload = function () { var tt = track.track; if (track.readyState >= 2) { if (tt.kind === 'metadata' && tt.mode !== 'hidden') { tt.mode = 'hidden'; } else if (tt.kind !== 'metadata' && tt.mode !== 'disabled') { tt.mode = 'disabled'; } track.onload = null; } }; this.remoteTextTracks().addTrack_(track.track); return track; }; /** * Remove remote text track from TextTrackList object * * @param {TextTrackObject} track Texttrack object to remove * @method removeRemoteTextTrack */ Html5.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { if (!this.featuresNativeTextTracks) { return _Tech.prototype.removeRemoteTextTrack.call(this, track); } var tracks, i; this.remoteTextTracks().removeTrack_(track); tracks = this.el().querySelectorAll('track'); for (i = 0; i < tracks.length; i++) { if (tracks[i] === track || tracks[i].track === track) { tracks[i].parentNode.removeChild(tracks[i]); break; } } }; return Html5; })(_Tech3['default']); /* HTML5 Support Testing ---------------------------------------------------- */ /* * Element for testing browser HTML5 video capabilities * * @type {Element} * @constant * @private */ Html5.TEST_VID = _document2['default'].createElement('video'); var track = _document2['default'].createElement('track'); track.kind = 'captions'; track.srclang = 'en'; track.label = 'English'; Html5.TEST_VID.appendChild(track); /* * Check if HTML5 video is supported by this browser/device * * @return {Boolean} */ Html5.isSupported = function () { // IE9 with no Media Player is a LIAR! (#984) try { Html5.TEST_VID.volume = 0.5; } catch (e) { return false; } return !!Html5.TEST_VID.canPlayType; }; // Add Source Handler pattern functions to this tech _Tech3['default'].withSourceHandlers(Html5); /* * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * * @param {Object} source The source object * @param {Html5} tech The instance of the HTML5 tech */ Html5.nativeSourceHandler = {}; /* * Check if the video element can handle the source natively * * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Html5.nativeSourceHandler.canHandleSource = function (source) { var match, ext; function canPlayType(type) { // IE9 on Windows 7 without MediaPlayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return Html5.TEST_VID.canPlayType(type); } catch (e) { return ''; } } // If a type was provided we should rely on that if (source.type) { return canPlayType(source.type); } else if (source.src) { // If no type, fall back to checking 'video/[EXTENSION]' ext = Url.getFileExtension(source.src); return canPlayType('video/' + ext); } return ''; }; /* * Pass the source to the video element * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * * @param {Object} source The source object * @param {Html5} tech The instance of the Html5 tech */ Html5.nativeSourceHandler.handleSource = function (source, tech) { tech.setSrc(source.src); }; /* * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ Html5.nativeSourceHandler.dispose = function () {}; // Register the native source handler Html5.registerSourceHandler(Html5.nativeSourceHandler); /* * Check if the volume can be changed in this browser/device. * Volume cannot be changed in a lot of mobile devices. * Specifically, it can't be changed from 1 on iOS. * * @return {Boolean} */ Html5.canControlVolume = function () { var volume = Html5.TEST_VID.volume; Html5.TEST_VID.volume = volume / 2 + 0.1; return volume !== Html5.TEST_VID.volume; }; /* * Check if playbackRate is supported in this browser/device. * * @return {Number} [description] */ Html5.canControlPlaybackRate = function () { var playbackRate = Html5.TEST_VID.playbackRate; Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1; return playbackRate !== Html5.TEST_VID.playbackRate; }; /* * Check to see if native text tracks are supported by this browser/device * * @return {Boolean} */ Html5.supportsNativeTextTracks = function () { var supportsTextTracks; // Figure out native text track support // If mode is a number, we cannot change it because it'll disappear from view. // Browsers with numeric modes include IE10 and older (<=2013) samsung android models. // Firefox isn't playing nice either with modifying the mode // TODO: Investigate firefox: https://github.com/videojs/video.js/issues/1862 supportsTextTracks = !!Html5.TEST_VID.textTracks; if (supportsTextTracks && Html5.TEST_VID.textTracks.length > 0) { supportsTextTracks = typeof Html5.TEST_VID.textTracks[0].mode !== 'number'; } if (supportsTextTracks && browser.IS_FIREFOX) { supportsTextTracks = false; } return supportsTextTracks; }; /* * Set the tech's volume control support status * * @type {Boolean} */ Html5.prototype.featuresVolumeControl = Html5.canControlVolume(); /* * Set the tech's playbackRate support status * * @type {Boolean} */ Html5.prototype.featuresPlaybackRate = Html5.canControlPlaybackRate(); /* * Set the tech's status on moving the video element. * In iOS, if you move a video element in the DOM, it breaks video playback. * * @type {Boolean} */ Html5.prototype.movingMediaElementInDOM = !browser.IS_IOS; /* * Set the the tech's fullscreen resize support status. * HTML video is able to automatically resize when going to fullscreen. * (No longer appears to be used. Can probably be removed.) */ Html5.prototype.featuresFullscreenResize = true; /* * Set the tech's progress event support status * (this disables the manual progress events of the Tech) */ Html5.prototype.featuresProgressEvents = true; /* * Sets the tech's status on native text track support * * @type {Boolean} */ Html5.prototype.featuresNativeTextTracks = Html5.supportsNativeTextTracks(); // HTML5 Feature detection and Device Fixes --------------------------------- // var canPlayType = undefined; var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i; var mp4RE = /^video\/mp4/i; Html5.patchCanPlayType = function () { // Android 4.0 and above can play HLS to some extent but it reports being unable to do so if (browser.ANDROID_VERSION >= 4) { if (!canPlayType) { canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType; } Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mpegurlRE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } // Override Android 2.2 and less canPlayType method which is broken if (browser.IS_OLD_ANDROID) { if (!canPlayType) { canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType; } Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mp4RE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } }; Html5.unpatchCanPlayType = function () { var r = Html5.TEST_VID.constructor.prototype.canPlayType; Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType; canPlayType = null; return r; }; // by default, patch the video element Html5.patchCanPlayType(); Html5.disposeMediaElement = function (el) { if (!el) { return; } if (el.parentNode) { el.parentNode.removeChild(el); } // remove any child track or source nodes to prevent their loading while (el.hasChildNodes()) { el.removeChild(el.firstChild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeAttribute('src'); // force the media element to update its loading state by calling load() // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793) if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function () { try { el.load(); } catch (e) {} })(); } }; _Component2['default'].registerComponent('Html5', Html5); exports['default'] = Html5; module.exports = exports['default']; // not supported },{"../component":52,"../utils/browser.js":108,"../utils/dom.js":111,"../utils/fn.js":113,"../utils/log.js":116,"../utils/merge-options.js":117,"../utils/url.js":120,"./tech.js":101,"global/document":1,"global/window":2,"object.assign":44}],100:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file loader.js */ var _Component2 = _dereq_('../component'); var _Component3 = _interopRequireWildcard(_Component2); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _toTitleCase = _dereq_('../utils/to-title-case.js'); var _toTitleCase2 = _interopRequireWildcard(_toTitleCase); /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class MediaLoader */ var MediaLoader = (function (_Component) { function MediaLoader(player, options, ready) { _classCallCheck(this, MediaLoader); _Component.call(this, player, options, ready); // If there are no sources when the player is initialized, // load the first supported playback technology. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) { for (var i = 0, j = options.playerOptions.techOrder; i < j.length; i++) { var techName = _toTitleCase2['default'](j[i]); var tech = _Component3['default'].getComponent(techName); // Check if the browser supports this technology if (tech && tech.isSupported()) { player.loadTech(techName); break; } } } else { // // Loop through playback technologies (HTML5, Flash) and check for support. // // Then load the best source. // // A few assumptions here: // // All playback technologies respect preload false. player.src(options.playerOptions.sources); } } _inherits(MediaLoader, _Component); return MediaLoader; })(_Component3['default']); _Component3['default'].registerComponent('MediaLoader', MediaLoader); exports['default'] = MediaLoader; module.exports = exports['default']; },{"../component":52,"../utils/to-title-case.js":119,"global/window":2}],101:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file tech.js * Media Technology Controller - Base class for media playback * technology controllers like Flash and HTML5 */ var _Component2 = _dereq_('../component'); var _Component3 = _interopRequireWildcard(_Component2); var _TextTrack = _dereq_('../tracks/text-track'); var _TextTrack2 = _interopRequireWildcard(_TextTrack); var _TextTrackList = _dereq_('../tracks/text-track-list'); var _TextTrackList2 = _interopRequireWildcard(_TextTrackList); var _import = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _log = _dereq_('../utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _createTimeRange = _dereq_('../utils/time-ranges.js'); var _bufferedPercent2 = _dereq_('../utils/buffer.js'); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); /** * Base class for media (HTML5 Video, Flash) controllers * * @param {Object=} options Options object * @param {Function=} ready Ready callback function * @extends Component * @class Tech */ var Tech = (function (_Component) { function Tech() { var options = arguments[0] === undefined ? {} : arguments[0]; var ready = arguments[1] === undefined ? function () {} : arguments[1]; _classCallCheck(this, Tech); // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; _Component.call(this, null, options, ready); // keep track of whether the current source has played at all to // implement a very limited played() this.hasStarted_ = false; this.on('playing', function () { this.hasStarted_ = true; }); this.on('loadstart', function () { this.hasStarted_ = false; }); this.textTracks_ = options.textTracks; // Manually track progress in cases where the browser/flash player doesn't report it. if (!this.featuresProgressEvents) { this.manualProgressOn(); } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if (!this.featuresTimeupdateEvents) { this.manualTimeUpdatesOn(); } this.initControlsListeners(); if (options.nativeCaptions === false || options.nativeTextTracks === false) { this.featuresNativeTextTracks = false; } if (!this.featuresNativeTextTracks) { this.emulateTextTracks(); } this.initTextTrackListeners(); // Turn on component tap events this.emitTapEvents(); } _inherits(Tech, _Component); /** * Set up click and touch listeners for the playback element * On desktops, a click on the video itself will toggle playback, * on a mobile device a click on the video toggles controls. * (toggling controls is done by toggling the user state between active and * inactive) * A tap can signal that a user has become active, or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold on * any controls will still keep the user active * * @method initControlsListeners */ Tech.prototype.initControlsListeners = function initControlsListeners() { // if we're loading the playback object after it has started loading or playing the // video (often with autoplay on) then the loadstart event has already fired and we // need to fire it manually because many things rely on it. // Long term we might consider how we would do this for other events like 'canplay' // that may also have fired. this.ready(function () { if (this.networkState && this.networkState() > 0) { this.trigger('loadstart'); } }); }; /* Fallbacks for unsupported event types ================================================================================ */ // Manually trigger progress events based on changes to the buffered amount // Many flash players and older HTML5 browsers don't send progress or progress-like events /** * Turn on progress events * * @method manualProgressOn */ Tech.prototype.manualProgressOn = function manualProgressOn() { this.on('durationchange', this.onDurationChange); this.manualProgress = true; // Trigger progress watching when a source begins loading this.one('ready', this.trackProgress); }; /** * Turn off progress events * * @method manualProgressOff */ Tech.prototype.manualProgressOff = function manualProgressOff() { this.manualProgress = false; this.stopTrackingProgress(); this.off('durationchange', this.onDurationChange); }; /** * Track progress * * @method trackProgress */ Tech.prototype.trackProgress = function trackProgress() { this.stopTrackingProgress(); this.progressInterval = this.setInterval(Fn.bind(this, function () { // Don't trigger unless buffered amount is greater than last time var numBufferedPercent = this.bufferedPercent(); if (this.bufferedPercent_ !== numBufferedPercent) { this.trigger('progress'); } this.bufferedPercent_ = numBufferedPercent; if (numBufferedPercent === 1) { this.stopTrackingProgress(); } }), 500); }; /** * Update duration * * @method onDurationChange */ Tech.prototype.onDurationChange = function onDurationChange() { this.duration_ = this.duration(); }; /** * Create and get TimeRange object for buffering * * @return {TimeRangeObject} * @method buffered */ Tech.prototype.buffered = function buffered() { return _createTimeRange.createTimeRange(0, 0); }; /** * Get buffered percent * * @return {Number} * @method bufferedPercent */ Tech.prototype.bufferedPercent = (function (_bufferedPercent) { function bufferedPercent() { return _bufferedPercent.apply(this, arguments); } bufferedPercent.toString = function () { return _bufferedPercent.toString(); }; return bufferedPercent; })(function () { return _bufferedPercent2.bufferedPercent(this.buffered(), this.duration_); }); /** * Stops tracking progress by clearing progress interval * * @method stopTrackingProgress */ Tech.prototype.stopTrackingProgress = function stopTrackingProgress() { this.clearInterval(this.progressInterval); }; /*! Time Tracking -------------------------------------------------------------- */ /** * Set event listeners for on play and pause and tracking current time * * @method manualTimeUpdatesOn */ Tech.prototype.manualTimeUpdatesOn = function manualTimeUpdatesOn() { this.manualTimeUpdates = true; this.on('play', this.trackCurrentTime); this.on('pause', this.stopTrackingCurrentTime); }; /** * Remove event listeners for on play and pause and tracking current time * * @method manualTimeUpdatesOff */ Tech.prototype.manualTimeUpdatesOff = function manualTimeUpdatesOff() { this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off('play', this.trackCurrentTime); this.off('pause', this.stopTrackingCurrentTime); }; /** * Tracks current time * * @method trackCurrentTime */ Tech.prototype.trackCurrentTime = function trackCurrentTime() { if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = this.setInterval(function () { this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }, 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }; /** * Turn off play progress tracking (when paused or dragging) * * @method stopTrackingCurrentTime */ Tech.prototype.stopTrackingCurrentTime = function stopTrackingCurrentTime() { this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen, // the progress bar won't make it all the way to the end this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }; /** * Turn off any manual progress or timeupdate tracking * * @method dispose */ Tech.prototype.dispose = function dispose() { // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } _Component.prototype.dispose.call(this); }; /** * Return the time ranges that have been played through for the * current source. This implementation is incomplete. It does not * track the played time ranges, only whether the source has played * at all or not. * @return {TimeRangeObject} a single time range if this video has * played or an empty set of ranges if not. * @method played */ Tech.prototype.played = function played() { if (this.hasStarted_) { return _createTimeRange.createTimeRange(0, 0); } return _createTimeRange.createTimeRange(); }; /** * Set current time * * @method setCurrentTime */ Tech.prototype.setCurrentTime = function setCurrentTime() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); } }; /** * Initialize texttrack listeners * * @method initTextTrackListeners */ Tech.prototype.initTextTrackListeners = function initTextTrackListeners() { var textTrackListChanges = Fn.bind(this, function () { this.trigger('texttrackchange'); }); var tracks = this.textTracks(); if (!tracks) { return; }tracks.addEventListener('removetrack', textTrackListChanges); tracks.addEventListener('addtrack', textTrackListChanges); this.on('dispose', Fn.bind(this, function () { tracks.removeEventListener('removetrack', textTrackListChanges); tracks.removeEventListener('addtrack', textTrackListChanges); })); }; /** * Emulate texttracks * * @method emulateTextTracks */ Tech.prototype.emulateTextTracks = function emulateTextTracks() { if (!_window2['default'].WebVTT && this.el().parentNode != null) { var script = _document2['default'].createElement('script'); script.src = this.options_['vtt.js'] || '../node_modules/vtt.js/dist/vtt.js'; this.el().parentNode.appendChild(script); _window2['default'].WebVTT = true; } var tracks = this.textTracks(); if (!tracks) { return; } var textTracksChanges = Fn.bind(this, function () { var _this = this; var updateDisplay = function updateDisplay() { return _this.trigger('texttrackchange'); }; updateDisplay(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); if (track.mode === 'showing') { track.addEventListener('cuechange', updateDisplay); } } }); tracks.addEventListener('change', textTracksChanges); this.on('dispose', function () { tracks.removeEventListener('change', textTracksChanges); }); }; /* * Provide default methods for text tracks. * * Html5 tech overrides these. */ /** * Get texttracks * * @returns {TextTrackList} * @method textTracks */ Tech.prototype.textTracks = function textTracks() { this.textTracks_ = this.textTracks_ || new _TextTrackList2['default'](); return this.textTracks_; }; /** * Get remote texttracks * * @returns {TextTrackList} * @method remoteTextTracks */ Tech.prototype.remoteTextTracks = function remoteTextTracks() { this.remoteTextTracks_ = this.remoteTextTracks_ || new _TextTrackList2['default'](); return this.remoteTextTracks_; }; /** * Creates and returns a remote text track object * * @param {String} kind Text track kind (subtitles, captions, descriptions * chapters and metadata) * @param {String=} label Label to identify the text track * @param {String=} language Two letter language abbreviation * @return {TextTrackObject} * @method addTextTrack */ Tech.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!kind) { throw new Error('TextTrack kind is required but was not provided'); } return createTrackHelper(this, kind, label, language); }; /** * Creates and returns a remote text track object * * @param {Object} options The object should contain values for * kind, language, label and src (location of the WebVTT file) * @return {TextTrackObject} * @method addRemoteTextTrack */ Tech.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) { var track = createTrackHelper(this, options.kind, options.label, options.language, options); this.remoteTextTracks().addTrack_(track); return { track: track }; }; /** * Remove remote texttrack * * @param {TextTrackObject} track Texttrack to remove * @method removeRemoteTextTrack */ Tech.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { this.textTracks().removeTrack_(track); this.remoteTextTracks().removeTrack_(track); }; /** * Provide a default setPoster method for techs * Poster support for techs should be optional, so we don't want techs to * break if they don't have a way to set a poster. * * @method setPoster */ Tech.prototype.setPoster = function setPoster() {}; return Tech; })(_Component3['default']); /* * List of associated text tracks * * @type {Array} * @private */ Tech.prototype.textTracks_; var createTrackHelper = function createTrackHelper(self, kind, label, language) { var options = arguments[4] === undefined ? {} : arguments[4]; var tracks = self.textTracks(); options.kind = kind; if (label) { options.label = label; } if (language) { options.language = language; } options.tech = self; var track = new _TextTrack2['default'](options); tracks.addTrack_(track); return track; }; Tech.prototype.featuresVolumeControl = true; // Resizing plugins using request fullscreen reloads the plugin Tech.prototype.featuresFullscreenResize = false; Tech.prototype.featuresPlaybackRate = false; // Optional events that we can manually mimic with timers // currently not triggered by video-js-swf Tech.prototype.featuresProgressEvents = false; Tech.prototype.featuresTimeupdateEvents = false; Tech.prototype.featuresNativeTextTracks = false; /* * A functional mixin for techs that want to use the Source Handler pattern. * * ##### EXAMPLE: * * Tech.withSourceHandlers.call(MyTech); * */ Tech.withSourceHandlers = function (_Tech) { /* * Register a source handler * Source handlers are scripts for handling specific formats. * The source handler pattern is used for adaptive formats (HLS, DASH) that * manually load video data and feed it into a Source Buffer (Media Source Extensions) * @param {Function} handler The source handler * @param {Boolean} first Register it before any existing handlers */ _Tech.registerSourceHandler = function (handler, index) { var handlers = _Tech.sourceHandlers; if (!handlers) { handlers = _Tech.sourceHandlers = []; } if (index === undefined) { // add to the end of the list index = handlers.length; } handlers.splice(index, 0, handler); }; /* * Return the first source handler that supports the source * TODO: Answer question: should 'probably' be prioritized over 'maybe' * @param {Object} source The source object * @returns {Object} The first source handler that supports the source * @returns {null} Null if no source handler is found */ _Tech.selectSourceHandler = function (source) { var handlers = _Tech.sourceHandlers || []; var can = undefined; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canHandleSource(source); if (can) { return handlers[i]; } } return null; }; /* * Check if the tech can support the given source * @param {Object} srcObj The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ _Tech.canPlaySource = function (srcObj) { var sh = _Tech.selectSourceHandler(srcObj); if (sh) { return sh.canHandleSource(srcObj); } return ''; }; /* * Create a function for setting the source using a source object * and source handlers. * Should never be called unless a source handler was found. * @param {Object} source A source object with src and type keys * @return {Tech} self */ _Tech.prototype.setSource = function (source) { var sh = _Tech.selectSourceHandler(source); if (!sh) { // Fall back to a native source hander when unsupported sources are // deliberately set if (_Tech.nativeSourceHandler) { sh = _Tech.nativeSourceHandler; } else { _log2['default'].error('No source hander found for the current source.'); } } // Dispose any existing source handler this.disposeSourceHandler(); this.off('dispose', this.disposeSourceHandler); this.currentSource_ = source; this.sourceHandler_ = sh.handleSource(source, this); this.on('dispose', this.disposeSourceHandler); this.originalSeekable_ = this.seekable; // when a source handler is registered, prefer its implementation of // seekable when present. this.seekable = function () { if (this.sourceHandler_ && this.sourceHandler_.seekable) { return this.sourceHandler_.seekable(); } return this.originalSeekable_.call(this); }; return this; }; /* * Clean up any existing source handler */ _Tech.prototype.disposeSourceHandler = function () { if (this.sourceHandler_ && this.sourceHandler_.dispose) { this.sourceHandler_.dispose(); this.seekable = this.originalSeekable_; } }; }; _Component3['default'].registerComponent('Tech', Tech); // Old name for Tech _Component3['default'].registerComponent('MediaTechController', Tech); exports['default'] = Tech; module.exports = exports['default']; },{"../component":52,"../tracks/text-track":107,"../tracks/text-track-list":105,"../utils/buffer.js":109,"../utils/fn.js":113,"../utils/log.js":116,"../utils/time-ranges.js":118,"global/document":1,"global/window":2}],102:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file text-track-cue-list.js */ var _import = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_import); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist * * interface TextTrackCueList { * readonly attribute unsigned long length; * getter TextTrackCue (unsigned long index); * TextTrackCue? getCueById(DOMString id); * }; */ var TextTrackCueList = (function (_TextTrackCueList) { function TextTrackCueList(_x) { return _TextTrackCueList.apply(this, arguments); } TextTrackCueList.toString = function () { return _TextTrackCueList.toString(); }; return TextTrackCueList; })(function (cues) { var list = this; if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in TextTrackCueList.prototype) { list[prop] = TextTrackCueList.prototype[prop]; } } TextTrackCueList.prototype.setCues_.call(list, cues); Object.defineProperty(list, 'length', { get: function get() { return this.length_; } }); if (browser.IS_IE8) { return list; } }); TextTrackCueList.prototype.setCues_ = function (cues) { var oldLength = this.length || 0; var i = 0; var l = cues.length; this.cues_ = cues; this.length_ = cues.length; var defineProp = function defineProp(i) { if (!('' + i in this)) { Object.defineProperty(this, '' + i, { get: function get() { return this.cues_[i]; } }); } }; if (oldLength < l) { i = oldLength; for (; i < l; i++) { defineProp.call(this, i); } } }; TextTrackCueList.prototype.getCueById = function (id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var cue = this[i]; if (cue.id === id) { result = cue; break; } } return result; }; exports['default'] = TextTrackCueList; module.exports = exports['default']; },{"../utils/browser.js":108,"global/document":1}],103:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file text-track-display.js */ var _Component2 = _dereq_('../component'); var _Component3 = _interopRequireWildcard(_Component2); var _Menu = _dereq_('../menu/menu.js'); var _Menu2 = _interopRequireWildcard(_Menu); var _MenuItem = _dereq_('../menu/menu-item.js'); var _MenuItem2 = _interopRequireWildcard(_MenuItem); var _MenuButton = _dereq_('../menu/menu-button.js'); var _MenuButton2 = _interopRequireWildcard(_MenuButton); var _import = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var darkGray = '#222'; var lightGray = '#ccc'; var fontMap = { monospace: 'monospace', sansSerif: 'sans-serif', serif: 'serif', monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace', monospaceSerif: '"Courier New", monospace', proportionalSansSerif: 'sans-serif', proportionalSerif: 'serif', casual: '"Comic Sans MS", Impact, fantasy', script: '"Monotype Corsiva", cursive', smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif' }; /** * The component for displaying text track cues * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class TextTrackDisplay */ var TextTrackDisplay = (function (_Component) { function TextTrackDisplay(player, options, ready) { _classCallCheck(this, TextTrackDisplay); _Component.call(this, player, options, ready); player.on('loadstart', Fn.bind(this, this.toggleDisplay)); player.on('texttrackchange', Fn.bind(this, this.updateDisplay)); // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. player.ready(Fn.bind(this, function () { if (player.tech && player.tech.featuresNativeTextTracks) { this.hide(); return; } player.on('fullscreenchange', Fn.bind(this, this.updateDisplay)); var tracks = this.options_.playerOptions.tracks || []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; this.player_.addRemoteTextTrack(track); } })); } _inherits(TextTrackDisplay, _Component); /** * Toggle display texttracks * * @method toggleDisplay */ TextTrackDisplay.prototype.toggleDisplay = function toggleDisplay() { if (this.player_.tech && this.player_.tech.featuresNativeTextTracks) { this.hide(); } else { this.show(); } }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ TextTrackDisplay.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }); }; /** * Clear display texttracks * * @method clearDisplay */ TextTrackDisplay.prototype.clearDisplay = function clearDisplay() { if (typeof _window2['default'].WebVTT === 'function') { _window2['default'].WebVTT.processCues(_window2['default'], [], this.el_); } }; /** * Update display texttracks * * @method updateDisplay */ TextTrackDisplay.prototype.updateDisplay = function updateDisplay() { var tracks = this.player_.textTracks(); this.clearDisplay(); if (!tracks) { return; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track.mode === 'showing') { this.updateForTrack(track); } } }; /** * Add texttrack to texttrack list * * @param {TextTrackObject} track Texttrack object to be added to list * @method updateForTrack */ TextTrackDisplay.prototype.updateForTrack = function updateForTrack(track) { if (typeof _window2['default'].WebVTT !== 'function' || !track.activeCues) { return; } var overrides = this.player_.textTrackSettings.getValues(); var cues = []; for (var _i = 0; _i < track.activeCues.length; _i++) { cues.push(track.activeCues[_i]); } _window2['default'].WebVTT.processCues(_window2['default'], track.activeCues, this.el_); var i = cues.length; while (i--) { var cueDiv = cues[i].displayState; if (overrides.color) { cueDiv.firstChild.style.color = overrides.color; } if (overrides.textOpacity) { tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity)); } if (overrides.backgroundColor) { cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor; } if (overrides.backgroundOpacity) { tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity)); } if (overrides.windowColor) { if (overrides.windowOpacity) { tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity)); } else { cueDiv.style.backgroundColor = overrides.windowColor; } } if (overrides.edgeStyle) { if (overrides.edgeStyle === 'dropshadow') { cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray; } else if (overrides.edgeStyle === 'raised') { cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray; } else if (overrides.edgeStyle === 'depressed') { cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray; } else if (overrides.edgeStyle === 'uniform') { cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray; } } if (overrides.fontPercent && overrides.fontPercent !== 1) { var fontSize = _window2['default'].parseFloat(cueDiv.style.fontSize); cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px'; cueDiv.style.height = 'auto'; cueDiv.style.top = 'auto'; cueDiv.style.bottom = '2px'; } if (overrides.fontFamily && overrides.fontFamily !== 'default') { if (overrides.fontFamily === 'small-caps') { cueDiv.firstChild.style.fontVariant = 'small-caps'; } else { cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily]; } } } }; return TextTrackDisplay; })(_Component3['default']); /** * Add cue HTML to display * * @param {Number} color Hex number for color, like #f0e * @param {Number} opacity Value for opacity,0.0 - 1.0 * @return {RGBAColor} In the form 'rgba(255, 0, 0, 0.3)' * @method constructColor */ function constructColor(color, opacity) { return 'rgba(' + // color looks like "#f0e" parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')'; } /** * Try to update style * Some style changes will throw an error, particularly in IE8. Those should be noops. * * @param {Element} el The element to be styles * @param {CSSProperty} style The CSS property to be styled * @param {CSSStyle} rule The actual style to be applied to the property * @method tryUpdateStyle */ function tryUpdateStyle(el, style, rule) { // try { el.style[style] = rule; } catch (e) {} } _Component3['default'].registerComponent('TextTrackDisplay', TextTrackDisplay); exports['default'] = TextTrackDisplay; module.exports = exports['default']; },{"../component":52,"../menu/menu-button.js":89,"../menu/menu-item.js":90,"../menu/menu.js":91,"../utils/fn.js":113,"global/document":1,"global/window":2}],104:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file text-track-enums.js * * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode * * enum TextTrackMode { "disabled", "hidden", "showing" }; */ var TextTrackMode = { disabled: 'disabled', hidden: 'hidden', showing: 'showing' }; /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackkind * * enum TextTrackKind { "subtitles", "captions", "descriptions", "chapters", "metadata" }; */ var TextTrackKind = { subtitles: 'subtitles', captions: 'captions', descriptions: 'descriptions', chapters: 'chapters', metadata: 'metadata' }; exports.TextTrackMode = TextTrackMode; exports.TextTrackKind = TextTrackKind; },{}],105:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file text-track-list.js */ var _EventTarget = _dereq_('../event-target'); var _EventTarget2 = _interopRequireWildcard(_EventTarget); var _import = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_import2); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist * * interface TextTrackList : EventTarget { * readonly attribute unsigned long length; * getter TextTrack (unsigned long index); * TextTrack? getTrackById(DOMString id); * * attribute EventHandler onchange; * attribute EventHandler onaddtrack; * attribute EventHandler onremovetrack; * }; */ var TextTrackList = (function (_TextTrackList) { function TextTrackList(_x) { return _TextTrackList.apply(this, arguments); } TextTrackList.toString = function () { return _TextTrackList.toString(); }; return TextTrackList; })(function (tracks) { var list = this; if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in TextTrackList.prototype) { list[prop] = TextTrackList.prototype[prop]; } } tracks = tracks || []; list.tracks_ = []; Object.defineProperty(list, 'length', { get: function get() { return this.tracks_.length; } }); for (var i = 0; i < tracks.length; i++) { list.addTrack_(tracks[i]); } if (browser.IS_IE8) { return list; } }); TextTrackList.prototype = Object.create(_EventTarget2['default'].prototype); TextTrackList.prototype.constructor = TextTrackList; /* * change - One or more tracks in the track list have been enabled or disabled. * addtrack - A track has been added to the track list. * removetrack - A track has been removed from the track list. */ TextTrackList.prototype.allowedEvents_ = { change: 'change', addtrack: 'addtrack', removetrack: 'removetrack' }; // emulate attribute EventHandler support to allow for feature detection for (var _event in TextTrackList.prototype.allowedEvents_) { TextTrackList.prototype['on' + _event] = null; } TextTrackList.prototype.addTrack_ = function (track) { var index = this.tracks_.length; if (!('' + index in this)) { Object.defineProperty(this, index, { get: function get() { return this.tracks_[index]; } }); } track.addEventListener('modechange', Fn.bind(this, function () { this.trigger('change'); })); this.tracks_.push(track); this.trigger({ type: 'addtrack', track: track }); }; TextTrackList.prototype.removeTrack_ = function (rtrack) { var result = null; var track = undefined; for (var i = 0, l = this.length; i < l; i++) { track = this[i]; if (track === rtrack) { this.tracks_.splice(i, 1); break; } } this.trigger({ type: 'removetrack', track: track }); }; TextTrackList.prototype.getTrackById = function (id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var track = this[i]; if (track.id === id) { result = track; break; } } return result; }; exports['default'] = TextTrackList; module.exports = exports['default']; },{"../event-target":83,"../utils/browser.js":108,"../utils/fn.js":113,"global/document":1}],106:[function(_dereq_,module,exports){ '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'); } }; 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) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file text-track-settings.js */ var _Component2 = _dereq_('../component'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../utils/events.js'); var Events = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import2); var _log = _dereq_('../utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _safeParseTuple2 = _dereq_('safe-json-parse/tuple'); var _safeParseTuple3 = _interopRequireWildcard(_safeParseTuple2); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); /** * Manipulate settings of texttracks * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class TextTrackSettings */ var TextTrackSettings = (function (_Component) { function TextTrackSettings(player, options) { _classCallCheck(this, TextTrackSettings); _Component.call(this, player, options); this.hide(); // Grab `persistTextTrackSettings` from the player options if not passed in child options if (options.persistTextTrackSettings === undefined) { this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings; } Events.on(this.el().querySelector('.vjs-done-button'), 'click', Fn.bind(this, function () { this.saveSettings(); this.hide(); })); Events.on(this.el().querySelector('.vjs-default-button'), 'click', Fn.bind(this, function () { this.el().querySelector('.vjs-fg-color > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-color > select').selectedIndex = 0; this.el().querySelector('.window-color > select').selectedIndex = 0; this.el().querySelector('.vjs-text-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-window-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-edge-style select').selectedIndex = 0; this.el().querySelector('.vjs-font-family select').selectedIndex = 0; this.el().querySelector('.vjs-font-percent select').selectedIndex = 2; this.updateDisplay(); })); Events.on(this.el().querySelector('.vjs-fg-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-bg-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.window-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-text-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-bg-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-window-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-font-percent select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-edge-style select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-font-family select'), 'change', Fn.bind(this, this.updateDisplay)); if (this.options_.persistTextTrackSettings) { this.restoreSettings(); } } _inherits(TextTrackSettings, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ TextTrackSettings.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-caption-settings vjs-modal-overlay', innerHTML: captionOptionsMenuTemplate() }); }; /** * Get texttrack settings * Settings are * .vjs-edge-style * .vjs-font-family * .vjs-fg-color * .vjs-text-opacity * .vjs-bg-color * .vjs-bg-opacity * .window-color * .vjs-window-opacity * * @return {Object} * @method getValues */ TextTrackSettings.prototype.getValues = function getValues() { var el = this.el(); var textEdge = getSelectedOptionValue(el.querySelector('.vjs-edge-style select')); var fontFamily = getSelectedOptionValue(el.querySelector('.vjs-font-family select')); var fgColor = getSelectedOptionValue(el.querySelector('.vjs-fg-color > select')); var textOpacity = getSelectedOptionValue(el.querySelector('.vjs-text-opacity > select')); var bgColor = getSelectedOptionValue(el.querySelector('.vjs-bg-color > select')); var bgOpacity = getSelectedOptionValue(el.querySelector('.vjs-bg-opacity > select')); var windowColor = getSelectedOptionValue(el.querySelector('.window-color > select')); var windowOpacity = getSelectedOptionValue(el.querySelector('.vjs-window-opacity > select')); var fontPercent = _window2['default'].parseFloat(getSelectedOptionValue(el.querySelector('.vjs-font-percent > select'))); var result = { backgroundOpacity: bgOpacity, textOpacity: textOpacity, windowOpacity: windowOpacity, edgeStyle: textEdge, fontFamily: fontFamily, color: fgColor, backgroundColor: bgColor, windowColor: windowColor, fontPercent: fontPercent }; for (var _name in result) { if (result[_name] === '' || result[_name] === 'none' || _name === 'fontPercent' && result[_name] === 1) { delete result[_name]; } } return result; }; /** * Set texttrack settings * Settings are * .vjs-edge-style * .vjs-font-family * .vjs-fg-color * .vjs-text-opacity * .vjs-bg-color * .vjs-bg-opacity * .window-color * .vjs-window-opacity * * @param {Object} values Object with texttrack setting values * @method setValues */ TextTrackSettings.prototype.setValues = function setValues(values) { var el = this.el(); setSelectedOption(el.querySelector('.vjs-edge-style select'), values.edgeStyle); setSelectedOption(el.querySelector('.vjs-font-family select'), values.fontFamily); setSelectedOption(el.querySelector('.vjs-fg-color > select'), values.color); setSelectedOption(el.querySelector('.vjs-text-opacity > select'), values.textOpacity); setSelectedOption(el.querySelector('.vjs-bg-color > select'), values.backgroundColor); setSelectedOption(el.querySelector('.vjs-bg-opacity > select'), values.backgroundOpacity); setSelectedOption(el.querySelector('.window-color > select'), values.windowColor); setSelectedOption(el.querySelector('.vjs-window-opacity > select'), values.windowOpacity); var fontPercent = values.fontPercent; if (fontPercent) { fontPercent = fontPercent.toFixed(2); } setSelectedOption(el.querySelector('.vjs-font-percent > select'), fontPercent); }; /** * Restore texttrack settings * * @method restoreSettings */ TextTrackSettings.prototype.restoreSettings = function restoreSettings() { var _safeParseTuple = _safeParseTuple3['default'](_window2['default'].localStorage.getItem('vjs-text-track-settings')); var err = _safeParseTuple[0]; var values = _safeParseTuple[1]; if (err) { _log2['default'].error(err); } if (values) { this.setValues(values); } }; /** * Save texttrack settings to local storage * * @method saveSettings */ TextTrackSettings.prototype.saveSettings = function saveSettings() { if (!this.options_.persistTextTrackSettings) { return; } var values = this.getValues(); try { if (Object.getOwnPropertyNames(values).length > 0) { _window2['default'].localStorage.setItem('vjs-text-track-settings', JSON.stringify(values)); } else { _window2['default'].localStorage.removeItem('vjs-text-track-settings'); } } catch (e) {} }; /** * Update display of texttrack settings * * @method updateDisplay */ TextTrackSettings.prototype.updateDisplay = function updateDisplay() { var ttDisplay = this.player_.getChild('textTrackDisplay'); if (ttDisplay) { ttDisplay.updateDisplay(); } }; return TextTrackSettings; })(_Component3['default']); _Component3['default'].registerComponent('TextTrackSettings', TextTrackSettings); function getSelectedOptionValue(target) { var selectedOption = undefined; // not all browsers support selectedOptions, so, fallback to options if (target.selectedOptions) { selectedOption = target.selectedOptions[0]; } else if (target.options) { selectedOption = target.options[target.options.selectedIndex]; } return selectedOption.value; } function setSelectedOption(target, value) { if (!value) { return; } var i = undefined; for (i = 0; i < target.options.length; i++) { var option = target.options[i]; if (option.value === value) { break; } } target.selectedIndex = i; } function captionOptionsMenuTemplate() { var template = '<div class="vjs-tracksettings">\n <div class="vjs-tracksettings-colors">\n <div class="vjs-fg-color vjs-tracksetting">\n <label class="vjs-label">Foreground</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-text-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Opaque</option>\n </select>\n </span>\n </div> <!-- vjs-fg-color -->\n <div class="vjs-bg-color vjs-tracksetting">\n <label class="vjs-label">Background</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-bg-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-bg-color -->\n <div class="window-color vjs-tracksetting">\n <label class="vjs-label">Window</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-window-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-window-color -->\n </div> <!-- vjs-tracksettings -->\n <div class="vjs-tracksettings-font">\n <div class="vjs-font-percent vjs-tracksetting">\n <label class="vjs-label">Font Size</label>\n <select>\n <option value="0.50">50%</option>\n <option value="0.75">75%</option>\n <option value="1.00" selected>100%</option>\n <option value="1.25">125%</option>\n <option value="1.50">150%</option>\n <option value="1.75">175%</option>\n <option value="2.00">200%</option>\n <option value="3.00">300%</option>\n <option value="4.00">400%</option>\n </select>\n </div> <!-- vjs-font-percent -->\n <div class="vjs-edge-style vjs-tracksetting">\n <label class="vjs-label">Text Edge Style</label>\n <select>\n <option value="none">None</option>\n <option value="raised">Raised</option>\n <option value="depressed">Depressed</option>\n <option value="uniform">Uniform</option>\n <option value="dropshadow">Dropshadow</option>\n </select>\n </div> <!-- vjs-edge-style -->\n <div class="vjs-font-family vjs-tracksetting">\n <label class="vjs-label">Font Family</label>\n <select>\n <option value="">Default</option>\n <option value="monospaceSerif">Monospace Serif</option>\n <option value="proportionalSerif">Proportional Serif</option>\n <option value="monospaceSansSerif">Monospace Sans-Serif</option>\n <option value="proportionalSansSerif">Proportional Sans-Serif</option>\n <option value="casual">Casual</option>\n <option value="script">Script</option>\n <option value="small-caps">Small Caps</option>\n </select>\n </div> <!-- vjs-font-family -->\n </div>\n </div>\n <div class="vjs-tracksettings-controls">\n <button class="vjs-default-button">Defaults</button>\n <button class="vjs-done-button">Done</button>\n </div>'; return template; } exports['default'] = TextTrackSettings; module.exports = exports['default']; },{"../component":52,"../utils/events.js":112,"../utils/fn.js":113,"../utils/log.js":116,"global/window":2,"safe-json-parse/tuple":49}],107:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file text-track.js */ var _TextTrackCueList = _dereq_('./text-track-cue-list'); var _TextTrackCueList2 = _interopRequireWildcard(_TextTrackCueList); var _import = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/guid.js'); var Guid = _interopRequireWildcard(_import2); var _import3 = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_import3); var _import4 = _dereq_('./text-track-enums'); var TextTrackEnum = _interopRequireWildcard(_import4); var _log = _dereq_('../utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _EventTarget = _dereq_('../event-target'); var _EventTarget2 = _interopRequireWildcard(_EventTarget); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _XHR = _dereq_('../xhr.js'); var _XHR2 = _interopRequireWildcard(_XHR); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack * * interface TextTrack : EventTarget { * readonly attribute TextTrackKind kind; * readonly attribute DOMString label; * readonly attribute DOMString language; * * readonly attribute DOMString id; * readonly attribute DOMString inBandMetadataTrackDispatchType; * * attribute TextTrackMode mode; * * readonly attribute TextTrackCueList? cues; * readonly attribute TextTrackCueList? activeCues; * * void addCue(TextTrackCue cue); * void removeCue(TextTrackCue cue); * * attribute EventHandler oncuechange; * }; */ var TextTrack = (function (_TextTrack) { function TextTrack() { return _TextTrack.apply(this, arguments); } TextTrack.toString = function () { return _TextTrack.toString(); }; return TextTrack; })(function () { var options = arguments[0] === undefined ? {} : arguments[0]; if (!options.tech) { throw new Error('A tech was not provided.'); } var tt = this; if (browser.IS_IE8) { tt = _document2['default'].createElement('custom'); for (var prop in TextTrack.prototype) { tt[prop] = TextTrack.prototype[prop]; } } tt.tech_ = options.tech; var mode = TextTrackEnum.TextTrackMode[options.mode] || 'disabled'; var kind = TextTrackEnum.TextTrackKind[options.kind] || 'subtitles'; var label = options.label || ''; var language = options.language || options.srclang || ''; var id = options.id || 'vjs_text_track_' + Guid.newGUID(); if (kind === 'metadata' || kind === 'chapters') { mode = 'hidden'; } tt.cues_ = []; tt.activeCues_ = []; var cues = new _TextTrackCueList2['default'](tt.cues_); var activeCues = new _TextTrackCueList2['default'](tt.activeCues_); var changed = false; var timeupdateHandler = Fn.bind(tt, function () { this.activeCues; if (changed) { this.trigger('cuechange'); changed = false; } }); if (mode !== 'disabled') { tt.tech_.on('timeupdate', timeupdateHandler); } Object.defineProperty(tt, 'kind', { get: function get() { return kind; }, set: Function.prototype }); Object.defineProperty(tt, 'label', { get: function get() { return label; }, set: Function.prototype }); Object.defineProperty(tt, 'language', { get: function get() { return language; }, set: Function.prototype }); Object.defineProperty(tt, 'id', { get: function get() { return id; }, set: Function.prototype }); Object.defineProperty(tt, 'mode', { get: function get() { return mode; }, set: function set(newMode) { if (!TextTrackEnum.TextTrackMode[newMode]) { return; } mode = newMode; if (mode === 'showing') { this.tech_.on('timeupdate', timeupdateHandler); } this.trigger('modechange'); } }); Object.defineProperty(tt, 'cues', { get: function get() { if (!this.loaded_) { return null; } return cues; }, set: Function.prototype }); Object.defineProperty(tt, 'activeCues', { get: function get() { if (!this.loaded_) { return null; } if (this.cues.length === 0) { return activeCues; // nothing to do } var ct = this.tech_.currentTime(); var active = []; for (var i = 0, l = this.cues.length; i < l; i++) { var cue = this.cues[i]; if (cue.startTime <= ct && cue.endTime >= ct) { active.push(cue); } else if (cue.startTime === cue.endTime && cue.startTime <= ct && cue.startTime + 0.5 >= ct) { active.push(cue); } } changed = false; if (active.length !== this.activeCues_.length) { changed = true; } else { for (var i = 0; i < active.length; i++) { if (indexOf.call(this.activeCues_, active[i]) === -1) { changed = true; } } } this.activeCues_ = active; activeCues.setCues_(this.activeCues_); return activeCues; }, set: Function.prototype }); if (options.src) { loadTrack(options.src, tt); } else { tt.loaded_ = true; } if (browser.IS_IE8) { return tt; } }); TextTrack.prototype = Object.create(_EventTarget2['default'].prototype); TextTrack.prototype.constructor = TextTrack; /* * cuechange - One or more cues in the track have become active or stopped being active. */ TextTrack.prototype.allowedEvents_ = { cuechange: 'cuechange' }; TextTrack.prototype.addCue = function (cue) { var tracks = this.tech_.textTracks(); if (tracks) { for (var i = 0; i < tracks.length; i++) { if (tracks[i] !== this) { tracks[i].removeCue(cue); } } } this.cues_.push(cue); this.cues.setCues_(this.cues_); }; TextTrack.prototype.removeCue = function (removeCue) { var removed = false; for (var i = 0, l = this.cues_.length; i < l; i++) { var cue = this.cues_[i]; if (cue === removeCue) { this.cues_.splice(i, 1); removed = true; } } if (removed) { this.cues.setCues_(this.cues_); } }; /* * Downloading stuff happens below this point */ var parseCues = (function (_parseCues) { function parseCues(_x, _x2) { return _parseCues.apply(this, arguments); } parseCues.toString = function () { return _parseCues.toString(); }; return parseCues; })(function (srcContent, track) { if (typeof _window2['default'].WebVTT !== 'function') { //try again a bit later return _window2['default'].setTimeout(function () { parseCues(srcContent, track); }, 25); } var parser = new _window2['default'].WebVTT.Parser(_window2['default'], _window2['default'].vttjs, _window2['default'].WebVTT.StringDecoder()); parser.oncue = function (cue) { track.addCue(cue); }; parser.onparsingerror = function (error) { _log2['default'].error(error); }; parser.parse(srcContent); parser.flush(); }); var loadTrack = function loadTrack(src, track) { _XHR2['default'](src, Fn.bind(this, function (err, response, responseBody) { if (err) { return _log2['default'].error(err); } track.loaded_ = true; parseCues(responseBody, track); })); }; var indexOf = function indexOf(searchElement, fromIndex) { if (this == null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (len === 0) { return -1; } var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } if (n >= len) { return -1; } var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); while (k < len) { if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; exports['default'] = TextTrack; module.exports = exports['default']; },{"../event-target":83,"../utils/browser.js":108,"../utils/fn.js":113,"../utils/guid.js":115,"../utils/log.js":116,"../xhr.js":122,"./text-track-cue-list":102,"./text-track-enums":104,"global/document":1,"global/window":2}],108:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file browser.js */ var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var USER_AGENT = _window2['default'].navigator.userAgent; /* * Device is an iPhone * * @type {Boolean} * @constant * @private */ var IS_IPHONE = /iPhone/i.test(USER_AGENT); exports.IS_IPHONE = IS_IPHONE; var IS_IPAD = /iPad/i.test(USER_AGENT); exports.IS_IPAD = IS_IPAD; var IS_IPOD = /iPod/i.test(USER_AGENT); exports.IS_IPOD = IS_IPOD; var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD; exports.IS_IOS = IS_IOS; var IOS_VERSION = (function () { var match = USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } })(); exports.IOS_VERSION = IOS_VERSION; var IS_ANDROID = /Android/i.test(USER_AGENT); exports.IS_ANDROID = IS_ANDROID; var ANDROID_VERSION = (function () { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i), major, minor; if (!match) { return null; } major = match[1] && parseFloat(match[1]); minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } else { return null; } })(); exports.ANDROID_VERSION = ANDROID_VERSION; // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser var IS_OLD_ANDROID = IS_ANDROID && /webkit/i.test(USER_AGENT) && ANDROID_VERSION < 2.3; exports.IS_OLD_ANDROID = IS_OLD_ANDROID; var IS_FIREFOX = /Firefox/i.test(USER_AGENT); exports.IS_FIREFOX = IS_FIREFOX; var IS_CHROME = /Chrome/i.test(USER_AGENT); exports.IS_CHROME = IS_CHROME; var IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT); exports.IS_IE8 = IS_IE8; var TOUCH_ENABLED = !!('ontouchstart' in _window2['default'] || _window2['default'].DocumentTouch && _document2['default'] instanceof _window2['default'].DocumentTouch); exports.TOUCH_ENABLED = TOUCH_ENABLED; var BACKGROUND_SIZE_SUPPORTED = ('backgroundSize' in _document2['default'].createElement('video').style); exports.BACKGROUND_SIZE_SUPPORTED = BACKGROUND_SIZE_SUPPORTED; },{"global/document":1,"global/window":2}],109:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * Compute how much your video has been buffered * * @param {Object} Buffered object * @param {Number} Total duration * @return {Number} Percent buffered of the total duration * @private * @function bufferedPercent */ exports.bufferedPercent = bufferedPercent; /** * @file buffer.js */ var _createTimeRange = _dereq_('./time-ranges.js'); function bufferedPercent(buffered, duration) { var bufferedDuration = 0, start, end; if (!duration) { return 0; } if (!buffered || !buffered.length) { buffered = _createTimeRange.createTimeRange(0, 0); } for (var i = 0; i < buffered.length; i++) { start = buffered.start(i); end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction if (end > duration) { end = duration; } bufferedDuration += end - start; } return bufferedDuration / duration; } },{"./time-ranges.js":118}],110:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; var _log = _dereq_('./log.js'); var _log2 = _interopRequireWildcard(_log); /** * Object containing the default behaviors for available handler methods. * * @private * @type {Object} */ var defaultBehaviors = { get: function get(obj, key) { return obj[key]; }, set: function set(obj, key, value) { obj[key] = value; return true; } }; /** * Expose private objects publicly using a Proxy to log deprecation warnings. * * Browsers that do not support Proxy objects will simply return the `target` * object, so it can be directly exposed. * * @param {Object} target The target object. * @param {Object} messages Messages to display from a Proxy. Only operations * with an associated message will be proxied. * @param {String} [messages.get] * @param {String} [messages.set] * @return {Object} A Proxy if supported or the `target` argument. */ exports['default'] = function (target) { var messages = arguments[1] === undefined ? {} : arguments[1]; if (typeof Proxy === 'function') { var _ret = (function () { var handler = {}; // Build a handler object based on those keys that have both messages // and default behaviors. Object.keys(messages).forEach(function (key) { if (defaultBehaviors.hasOwnProperty(key)) { handler[key] = function () { _log2['default'].warn(messages[key]); return defaultBehaviors[key].apply(this, arguments); }; } }); return { v: new Proxy(target, handler) }; })(); if (typeof _ret === 'object') return _ret.v; } return target; }; module.exports = exports['default']; },{"./log.js":116}],111:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * Shorthand for document.getElementById() * Also allows for CSS (jQuery) ID syntax. But nothing other than IDs. * * @param {String} id Element ID * @return {Element} Element with supplied ID * @function getEl */ exports.getEl = getEl; /** * Creates an element and applies properties. * * @param {String=} tagName Name of tag to be created. * @param {Object=} properties Element properties to be applied. * @return {Element} * @function createEl */ exports.createEl = createEl; /** * Insert an element as the first child node of another * * @param {Element} child Element to insert * @param {Element} parent Element to insert child into * @private * @function insertElFirst */ exports.insertElFirst = insertElFirst; /** * Returns the cache object where data for an element is stored * * @param {Element} el Element to store data for. * @return {Object} * @function getElData */ exports.getElData = getElData; /** * Returns whether or not an element has cached data * * @param {Element} el A dom element * @return {Boolean} * @private * @function hasElData */ exports.hasElData = hasElData; /** * Delete data for the element from the cache and the guid attr from getElementById * * @param {Element} el Remove data for an element * @private * @function removeElData */ exports.removeElData = removeElData; /** * Check if an element has a CSS class * * @param {Element} element Element to check * @param {String} classToCheck Classname to check * @function hasElClass */ exports.hasElClass = hasElClass; /** * Add a CSS class name to an element * * @param {Element} element Element to add class name to * @param {String} classToAdd Classname to add * @function addElClass */ exports.addElClass = addElClass; /** * Remove a CSS class name from an element * * @param {Element} element Element to remove from class name * @param {String} classToRemove Classname to remove * @function removeElClass */ exports.removeElClass = removeElClass; /** * Apply attributes to an HTML element. * * @param {Element} el Target element. * @param {Object=} attributes Element attributes to be applied. * @private * @function setElAttributes */ exports.setElAttributes = setElAttributes; /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * * @param {Element} tag Element from which to get tag attributes * @return {Object} * @private * @function getElAttributes */ exports.getElAttributes = getElAttributes; /** * Attempt to block the ability to select text while dragging controls * * @return {Boolean} * @method blockTextSelection */ exports.blockTextSelection = blockTextSelection; /** * Turn off text selection blocking * * @return {Boolean} * @method unblockTextSelection */ exports.unblockTextSelection = unblockTextSelection; /** * Offset Left * getBoundingClientRect technique from * John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/ * * @param {Element} el Element from which to get offset * @return {Object=} * @method findElPosition */ exports.findElPosition = findElPosition; /** * @file dom.js */ var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _import = _dereq_('./guid.js'); var Guid = _interopRequireWildcard(_import); function getEl(id) { if (id.indexOf('#') === 0) { id = id.slice(1); } return _document2['default'].getElementById(id); } function createEl() { var tagName = arguments[0] === undefined ? 'div' : arguments[0]; var properties = arguments[1] === undefined ? {} : arguments[1]; var el = _document2['default'].createElement(tagName); Object.getOwnPropertyNames(properties).forEach(function (propName) { var val = properties[propName]; // Not remembering why we were checking for dash // but using setAttribute means you have to use getAttribute // The check for dash checks for the aria- * attributes, like aria-label, aria-valuemin. // The additional check for "role" is because the default method for adding attributes does not // add the attribute "role". My guess is because it's not a valid attribute in some namespaces, although // browsers handle the attribute just fine. The W3C allows for aria- * attributes to be used in pre-HTML5 docs. // http://www.w3.org/TR/wai-aria-primer/#ariahtml. Using setAttribute gets around this problem. if (propName.indexOf('aria-') !== -1 || propName === 'role') { el.setAttribute(propName, val); } else { el[propName] = val; } }); return el; } function insertElFirst(child, parent) { if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } } /** * Element Data Store. Allows for binding data to an element without putting it directly on the element. * Ex. Event listeners are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * * @type {Object} * @private */ var elData = {}; /* * Unique attribute name to store an element's guid in * * @type {String} * @constant * @private */ var elIdAttr = 'vdata' + new Date().getTime(); function getElData(el) { var id = el[elIdAttr]; if (!id) { id = el[elIdAttr] = Guid.newGUID(); } if (!elData[id]) { elData[id] = {}; } return elData[id]; } function hasElData(el) { var id = el[elIdAttr]; if (!id) { return false; } return !!Object.getOwnPropertyNames(elData[id]).length; } function removeElData(el) { var id = el[elIdAttr]; if (!id) { return; } // Remove all stored data delete elData[id]; // Remove the elIdAttr property from the DOM node try { delete el[elIdAttr]; } catch (e) { if (el.removeAttribute) { el.removeAttribute(elIdAttr); } else { // IE doesn't appear to support removeAttribute on the document element el[elIdAttr] = null; } } } function hasElClass(element, classToCheck) { return (' ' + element.className + ' ').indexOf(' ' + classToCheck + ' ') !== -1; } function addElClass(element, classToAdd) { if (!hasElClass(element, classToAdd)) { element.className = element.className === '' ? classToAdd : element.className + ' ' + classToAdd; } } function removeElClass(element, classToRemove) { if (!hasElClass(element, classToRemove)) { return; } var classNames = element.className.split(' '); // no arr.indexOf in ie8, and we don't want to add a big shim for (var i = classNames.length - 1; i >= 0; i--) { if (classNames[i] === classToRemove) { classNames.splice(i, 1); } } element.className = classNames.join(' '); } function setElAttributes(el, attributes) { Object.getOwnPropertyNames(attributes).forEach(function (attrName) { var attrValue = attributes[attrName]; if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) { el.removeAttribute(attrName); } else { el.setAttribute(attrName, attrValue === true ? '' : attrValue); } }); } function getElAttributes(tag) { var obj, knownBooleans, attrs, attrName, attrVal; obj = {}; // known boolean attributes // we can check for matching boolean properties, but older browsers // won't know about HTML5 boolean attributes that we still read from knownBooleans = ',' + 'autoplay,controls,loop,muted,default' + ','; if (tag && tag.attributes && tag.attributes.length > 0) { attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { attrName = attrs[i].name; attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = attrVal !== null ? true : false; } obj[attrName] = attrVal; } } return obj; } function blockTextSelection() { _document2['default'].body.focus(); _document2['default'].onselectstart = function () { return false; }; } function unblockTextSelection() { _document2['default'].onselectstart = function () { return true; }; } function findElPosition(el) { var box = undefined; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } var docEl = _document2['default'].documentElement; var body = _document2['default'].body; var clientLeft = docEl.clientLeft || body.clientLeft || 0; var scrollLeft = _window2['default'].pageXOffset || body.scrollLeft; var left = box.left + scrollLeft - clientLeft; var clientTop = docEl.clientTop || body.clientTop || 0; var scrollTop = _window2['default'].pageYOffset || body.scrollTop; var top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: Math.round(left), top: Math.round(top) }; } },{"./guid.js":115,"global/document":1,"global/window":2}],112:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem Element or object to bind listeners to * @param {String|Array} type Type of event to bind to. * @param {Function} fn Event listener. * @method on */ exports.on = on; /** * Removes event listeners from an element * * @param {Element|Object} elem Object to remove listeners from * @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type. * @method off */ exports.off = off; /** * Trigger an event for an element * * @param {Element|Object} elem Element to trigger an event on * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Boolean=} Returned only if default was prevented * @method trigger */ exports.trigger = trigger; /** * Trigger a listener only once for an event * * @param {Element|Object} elem Element or object to * @param {String|Array} type Name/type of event * @param {Function} fn Event handler function * @method one */ exports.one = one; /** * Fix a native event to have standard property values * * @param {Object} event Event object to fix * @return {Object} * @private * @method fixEvent */ exports.fixEvent = fixEvent; /** * @file events.js * * Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. */ var _import = _dereq_('./dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('./guid.js'); var Guid = _interopRequireWildcard(_import2); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); function on(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(on, elem, type, fn); } var data = Dom.getElData(elem); // We need a place to store all our handler data if (!data.handlers) data.handlers = {}; if (!data.handlers[type]) data.handlers[type] = []; if (!fn.guid) fn.guid = Guid.newGUID(); data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event, hash) { if (data.disabled) return; event = fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { handlersCopy[m].call(elem, event, hash); } } } }; } if (data.handlers[type].length === 1) { if (elem.addEventListener) { elem.addEventListener(type, data.dispatcher, false); } else if (elem.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } } function off(elem, type, fn) { // Don't want to add a cache object through getElData if not needed if (!Dom.hasElData(elem)) { return; }var data = Dom.getElData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (Array.isArray(type)) { return _handleMultipleEvents(off, elem, type, fn); } // Utility function var removeType = function removeType(t) { data.handlers[t] = []; _cleanUpEvents(elem, t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) { removeType(t); }return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) { return; } // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } _cleanUpEvents(elem, type); } function trigger(elem, event, hash) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasElData first. var elemData = Dom.hasElData(elem) ? Dom.getElData(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type: event, target: elem }; } // Normalizes the event properties. event = fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event, hash); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles === true) { trigger.call(null, parent, event, hash); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented) { var targetData = Dom.getElData(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.defaultPrevented; } function one(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(one, elem, type, fn); } var func = (function (_func) { function func() { return _func.apply(this, arguments); } func.toString = function () { return _func.toString(); }; return func; })(function () { off(elem, type, func); fn.apply(this, arguments); }); // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || Guid.newGUID(); on(elem, type, func); } function fixEvent(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { var old = event || _window2['default'].event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key === 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || _document2['default']; } // Handle which other element the event is related to if (!event.relatedTarget) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; event.defaultPrevented = true; }; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX != null) { var doc = _document2['default'].documentElement, body = _document2['default'].body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button != null) { event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0; } } // Returns fixed-up instance return event; } /** * Clean up the listener cache and dispatchers * * @param {Element|Object} elem Element to clean up * @param {String} type Type of event to clean up * @private * @method _cleanUpEvents */ function _cleanUpEvents(elem, type) { var data = Dom.getElData(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (elem.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (Object.getOwnPropertyNames(data.handlers).length <= 0) { delete data.handlers; delete data.dispatcher; delete data.disabled; } // Finally remove the element data if there is no data left if (Object.getOwnPropertyNames(data).length === 0) { Dom.removeElData(elem); } } /** * Loops through an array of event types and calls the requested method for each type. * * @param {Function} fn The event method we want to use. * @param {Element|Object} elem Element or object to bind listeners to * @param {String} type Type of event to bind to. * @param {Function} callback Event listener. * @private * @function _handleMultipleEvents */ function _handleMultipleEvents(fn, elem, types, callback) { types.forEach(function (type) { //Call the event method for each one of the types fn(elem, type, callback); }); } },{"./dom.js":111,"./guid.js":115,"global/document":1,"global/window":2}],113:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file fn.js */ var _newGUID = _dereq_('./guid.js'); /** * Bind (a.k.a proxy or Context). A simple method for changing the context of a function * It also stores a unique id on the function so it can be easily removed from events * * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} * @private * @method bind */ var bind = function bind(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = _newGUID.newGUID(); } // Create the new function that changes the context var ret = function ret() { return fn.apply(context, arguments); }; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks ret.guid = uid ? uid + '_' + fn.guid : fn.guid; return ret; }; exports.bind = bind; },{"./guid.js":115}],114:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file format-time.js * * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @private * @function formatTime */ function formatTime(seconds) { var guide = arguments[1] === undefined ? seconds : arguments[1]; return (function () { var s = Math.floor(seconds % 60); var m = Math.floor(seconds / 60 % 60); var h = Math.floor(seconds / 3600); var gm = Math.floor(guide / 60 % 60); var gh = Math.floor(guide / 3600); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // Check if we need to show hours h = h > 0 || gh > 0 ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = s < 10 ? '0' + s : s; return h + m + s; })(); } exports['default'] = formatTime; module.exports = exports['default']; },{}],115:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; /** * Get the next unique ID * * @return {String} * @function newGUID */ exports.newGUID = newGUID; /** * @file guid.js * * Unique ID for an element or function * @type {Number} * @private */ var _guid = 1; function newGUID() { return _guid++; } },{}],116:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file log.js */ var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); /** * Log plain debug messages */ var log = function log() { _logType(null, arguments); }; /** * Keep a history of log messages * @type {Array} */ log.history = []; /** * Log error messages */ log.error = function () { _logType('error', arguments); }; /** * Log warning messages */ log.warn = function () { _logType('warn', arguments); }; /** * Log messages to the console and history based on the type of message * * @param {String} type The type of message, or `null` for `log` * @param {Object} args The args to be passed to the log * @private * @method _logType */ function _logType(type, args) { // convert args to an array to get array functions var argsArray = Array.prototype.slice.call(args); // if there's no console then don't try to output messages // they will still be stored in log.history // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist var noop = function noop() {}; var console = _window2['default'].console || { log: noop, warn: noop, error: noop }; if (type) { // add the type to the front of the message argsArray.unshift(type.toUpperCase() + ':'); } else { // default to log with no prefix type = 'log'; } // add to history log.history.push(argsArray); // add console prefix after adding to history argsArray.unshift('VIDEOJS:'); // call appropriate log function if (console[type].apply) { console[type].apply(console, argsArray); } else { // ie8 doesn't allow error.apply, but it will just join() the array anyway console[type](argsArray.join(' ')); } } exports['default'] = log; module.exports = exports['default']; },{"global/window":2}],117:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * Merge two options objects, recursively merging **only* * plain object * properties. Previously `deepMerge`. * * @param {Object} object The destination object * @param {...Object} source One or more objects to merge into the first * @returns {Object} The updated first object * @function mergeOptions */ exports['default'] = mergeOptions; /** * @file merge-options.js */ var _merge = _dereq_('lodash-compat/object/merge'); var _merge2 = _interopRequireWildcard(_merge); function isPlain(obj) { return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object; } function mergeOptions() { var object = arguments[0] === undefined ? {} : arguments[0]; // Allow for infinite additional object args to merge Array.prototype.slice.call(arguments, 1).forEach(function (source) { // Recursively merge only plain objects // All other values will be directly copied _merge2['default'](object, source, function (a, b) { // If we're not working with a plain object, copy the value as is if (!isPlain(b)) { return b; } // If the new value is a plain object but the first object value is not // we need to create a new object for the first object to merge with. // This makes it consistent with how merge() works by default // and also protects from later changes the to first object affecting // the second object's values. if (!isPlain(a)) { return mergeOptions({}, b); } }); }); return object; } module.exports = exports['default']; },{"lodash-compat/object/merge":40}],118:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file time-ranges.js * * Should create a fake TimeRange object * Mimics an HTML5 time range instance, which has functions that * return the start and end times for a range * TimeRanges are returned by the buffered() method * * @param {Number} start Start time in seconds * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @private * @method createTimeRange */ exports.createTimeRange = createTimeRange; function createTimeRange(start, end) { if (start === undefined && end === undefined) { return { length: 0, start: function start() { throw new Error('This TimeRanges object is empty'); }, end: function end() { throw new Error('This TimeRanges object is empty'); } }; } return { length: 1, start: (function (_start) { function start() { return _start.apply(this, arguments); } start.toString = function () { return _start.toString(); }; return start; })(function () { return start; }), end: (function (_end) { function end() { return _end.apply(this, arguments); } end.toString = function () { return _end.toString(); }; return end; })(function () { return end; }) }; } },{}],119:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; /** * @file to-title-case.js * * Uppercase the first letter of a string * * @param {String} string String to be uppercased * @return {String} * @private * @method toTitleCase */ function toTitleCase(string) { return string.charAt(0).toUpperCase() + string.slice(1); } exports["default"] = toTitleCase; module.exports = exports["default"]; },{}],120:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file url.js */ var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); /** * Resolve and parse the elements of a URL * * @param {String} url The url to parse * @return {Object} An object of url details * @method parseUrl */ var parseUrl = function parseUrl(url) { var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL var a = _document2['default'].createElement('a'); a.href = url; // IE8 (and 9?) Fix // ie8 doesn't parse the URL correctly until the anchor is actually // added to the body, and an innerHTML is needed to trigger the parsing var addToBody = a.host === '' && a.protocol !== 'file:'; var div = undefined; if (addToBody) { div = _document2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '"></a>'; a = div.firstChild; // prevent the div from affecting layout div.setAttribute('style', 'display:none; position:absolute;'); _document2['default'].body.appendChild(div); } // Copy the specific URL properties to a new object // This is also needed for IE8 because the anchor loses its // properties when it's removed from the dom var details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } // IE9 adds the port to the host property unlike everyone else. If // a port identifier is added for standard ports, strip it. if (details.protocol === 'http:') { details.host = details.host.replace(/:80$/, ''); } if (details.protocol === 'https:') { details.host = details.host.replace(/:443$/, ''); } if (addToBody) { _document2['default'].body.removeChild(div); } return details; }; exports.parseUrl = parseUrl; /** * Get absolute version of relative URL. Used to tell flash correct URL. * http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue * * @param {String} url URL to make absolute * @return {String} Absolute URL * @private * @method getAbsoluteURL */ var getAbsoluteURL = function getAbsoluteURL(url) { // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. var div = _document2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '">x</a>'; url = div.firstChild.href; } return url; }; exports.getAbsoluteURL = getAbsoluteURL; /** * Returns the extension of the passed file name. It will return an empty string if you pass an invalid path * * @param {String} path The fileName path like '/path/to/file.mp4' * @returns {String} The extension in lower case or an empty string if no extension could be found. * @method getFileExtension */ var getFileExtension = function getFileExtension(path) { if (typeof path === 'string') { var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i; var pathParts = splitPathRe.exec(path); if (pathParts) { return pathParts.pop().toLowerCase(); } } return ''; }; exports.getFileExtension = getFileExtension; },{"global/document":1}],121:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file video.js */ var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _import = _dereq_('./setup'); var setup = _interopRequireWildcard(_import); var _Component = _dereq_('./component'); var _Component2 = _interopRequireWildcard(_Component); var _EventTarget = _dereq_('./event-target'); var _EventTarget2 = _interopRequireWildcard(_EventTarget); var _globalOptions = _dereq_('./global-options.js'); var _globalOptions2 = _interopRequireWildcard(_globalOptions); var _Player = _dereq_('./player'); var _Player2 = _interopRequireWildcard(_Player); var _plugin = _dereq_('./plugins.js'); var _plugin2 = _interopRequireWildcard(_plugin); var _mergeOptions = _dereq_('../../src/js/utils/merge-options.js'); var _mergeOptions2 = _interopRequireWildcard(_mergeOptions); var _import2 = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_import2); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); var _createTimeRange = _dereq_('./utils/time-ranges.js'); var _log = _dereq_('./utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _xhr = _dereq_('./xhr.js'); var _xhr2 = _interopRequireWildcard(_xhr); var _import3 = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_import3); var _import4 = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_import4); var _import5 = _dereq_('./utils/url.js'); var Url = _interopRequireWildcard(_import5); var _extendsFn = _dereq_('./extends.js'); var _extendsFn2 = _interopRequireWildcard(_extendsFn); var _merge2 = _dereq_('lodash-compat/object/merge'); var _merge3 = _interopRequireWildcard(_merge2); var _createDeprecationProxy = _dereq_('./utils/create-deprecation-proxy.js'); var _createDeprecationProxy2 = _interopRequireWildcard(_createDeprecationProxy); // Include the built-in techs var _Html5 = _dereq_('./tech/html5.js'); var _Html52 = _interopRequireWildcard(_Html5); var _Flash = _dereq_('./tech/flash.js'); var _Flash2 = _interopRequireWildcard(_Flash); // HTML5 Element Shim for IE8 if (typeof HTMLVideoElement === 'undefined') { _document2['default'].createElement('video'); _document2['default'].createElement('audio'); _document2['default'].createElement('track'); } /** * Doubles as the main function for users to create a player instance and also * the main library object. * The `videojs` function can be used to initialize or retrieve a player. * ```js * var myPlayer = videojs('my_video_id'); * ``` * * @param {String|Element} id Video element or video element ID * @param {Object=} options Optional options object for config/settings * @param {Function=} ready Optional ready callback * @return {Player} A player instance * @mixes videojs * @method videojs */ var videojs = function videojs(id, options, ready) { var tag; // Element of ID // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (_Player2['default'].players[id]) { // If options or ready funtion are passed, warn if (options) { _log2['default'].warn('Player "' + id + '" is already initialised. Options will not be applied.'); } if (ready) { _Player2['default'].players[id].ready(ready); } return _Player2['default'].players[id]; // Otherwise get element for ID } else { tag = Dom.getEl(id); } // ID is a media element } else { tag = id; } // Check for a useable element if (!tag || !tag.nodeName) { // re: nodeName, could be a box div also throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns } // Element may have a player attr referring to an already created player instance. // If not, set up a new player and return the instance. return tag.player || new _Player2['default'](tag, options, ready); }; // Run Auto-load players // You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version) setup.autoSetupTimeout(1, videojs); /* * Current software version (semver) * * @type {String} */ videojs.VERSION = '5.0.0-rc.33'; /** * Get the global options object * * @return {Object} The global options object * @mixes videojs * @method getGlobalOptions */ videojs.getGlobalOptions = function () { return _globalOptions2['default']; }; /** * For backward compatibility, expose global options. * * @deprecated * @memberOf videojs * @property {Object|Proxy} options */ videojs.options = _createDeprecationProxy2['default'](_globalOptions2['default'], { get: 'Access to videojs.options is deprecated; use videojs.getGlobalOptions instead', set: 'Modification of videojs.options is deprecated; use videojs.setGlobalOptions instead' }); /** * Set options that will apply to every player * ```js * videojs.setGlobalOptions({ * autoplay: true * }); * // -> all players will autoplay by default * ``` * NOTE: This will do a deep merge with the new options, * not overwrite the entire global options object. * * @return {Object} The updated global options object * @mixes videojs * @method setGlobalOptions */ videojs.setGlobalOptions = function (newOptions) { return _mergeOptions2['default'](_globalOptions2['default'], newOptions); }; /** * Get an object with the currently created players, keyed by player ID * * @return {Object} The created players * @mixes videojs * @method getPlayers */ videojs.getPlayers = function () { return _Player2['default'].players; }; /** * For backward compatibility, expose players object. * * @deprecated * @memberOf videojs * @property {Object|Proxy} players */ videojs.players = _createDeprecationProxy2['default'](_Player2['default'].players, { get: 'Access to videojs.players is deprecated; use videojs.getPlayers instead', set: 'Modification of videojs.players is deprecated' }); /** * Get a component class object by name * ```js * var VjsButton = videojs.getComponent('Button'); * // Create a new instance of the component * var myButton = new VjsButton(myPlayer); * ``` * * @return {Component} Component identified by name * @mixes videojs * @method getComponent */ videojs.getComponent = _Component2['default'].getComponent; /** * Register a component so it can referred to by name * Used when adding to other * components, either through addChild * `component.addChild('myComponent')` * or through default children options * `{ children: ['myComponent'] }`. * ```js * // Get a component to subclass * var VjsButton = videojs.getComponent('Button'); * // Subclass the component (see 'extends' doc for more info) * var MySpecialButton = videojs.extends(VjsButton, {}); * // Register the new component * VjsButton.registerComponent('MySepcialButton', MySepcialButton); * // (optionally) add the new component as a default player child * myPlayer.addChild('MySepcialButton'); * ``` * NOTE: You could also just initialize the component before adding. * `component.addChild(new MyComponent());` * * @param {String} The class name of the component * @param {Component} The component class * @return {Component} The newly registered component * @mixes videojs * @method registerComponent */ videojs.registerComponent = _Component2['default'].registerComponent; /** * A suite of browser and device tests * * @type {Object} * @private */ videojs.browser = browser; /** * Whether or not the browser supports touch events. Included for backward * compatibility with 4.x, but deprecated. Use `videojs.browser.TOUCH_ENABLED` * instead going forward. * * @deprecated * @type {Boolean} */ videojs.TOUCH_ENABLED = browser.TOUCH_ENABLED; /** * Subclass an existing class * Mimics ES6 subclassing with the `extends` keyword * ```js * // Create a basic javascript 'class' * function MyClass(name){ * // Set a property at initialization * this.myName = name; * } * // Create an instance method * MyClass.prototype.sayMyName = function(){ * alert(this.myName); * }; * // Subclass the exisitng class and change the name * // when initializing * var MySubClass = videojs.extends(MyClass, { * constructor: function(name) { * // Call the super class constructor for the subclass * MyClass.call(this, name) * } * }); * // Create an instance of the new sub class * var myInstance = new MySubClass('John'); * myInstance.sayMyName(); // -> should alert "John" * ``` * * @param {Function} The Class to subclass * @param {Object} An object including instace methods for the new class * Optionally including a `constructor` function * @return {Function} The newly created subclass * @mixes videojs * @method extends */ videojs['extends'] = _extendsFn2['default']; /** * Merge two options objects recursively * Performs a deep merge like lodash.merge but **only merges plain objects** * (not arrays, elements, anything else) * Other values will be copied directly from the second object. * ```js * var defaultOptions = { * foo: true, * bar: { * a: true, * b: [1,2,3] * } * }; * var newOptions = { * foo: false, * bar: { * b: [4,5,6] * } * }; * var result = videojs.mergeOptions(defaultOptions, newOptions); * // result.foo = false; * // result.bar.a = true; * // result.bar.b = [4,5,6]; * ``` * * @param {Object} The options object whose values will be overriden * @param {Object} The options object with values to override the first * @param {Object} Any number of additional options objects * * @return {Object} a new object with the merged values * @mixes videojs * @method mergeOptions */ videojs.mergeOptions = _mergeOptions2['default']; /** * Change the context (this) of a function * * videojs.bind(newContext, function(){ * this === newContext * }); * * NOTE: as of v5.0 we require an ES5 shim, so you should use the native * `function(){}.bind(newContext);` instead of this. * * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} */ videojs.bind = Fn.bind; /** * Create a Video.js player plugin * Plugins are only initialized when options for the plugin are included * in the player options, or the plugin function on the player instance is * called. * **See the plugin guide in the docs for a more detailed example** * ```js * // Make a plugin that alerts when the player plays * videojs.plugin('myPlugin', function(myPluginOptions) { * myPluginOptions = myPluginOptions || {}; * * var player = this; * var alertText = myPluginOptions.text || 'Player is playing!' * * player.on('play', function(){ * alert(alertText); * }); * }); * // USAGE EXAMPLES * // EXAMPLE 1: New player with plugin options, call plugin immediately * var player1 = videojs('idOne', { * myPlugin: { * text: 'Custom text!' * } * }); * // Click play * // --> Should alert 'Custom text!' * // EXAMPLE 3: New player, initialize plugin later * var player3 = videojs('idThree'); * // Click play * // --> NO ALERT * // Click pause * // Initialize plugin using the plugin function on the player instance * player3.myPlugin({ * text: 'Plugin added later!' * }); * // Click play * // --> Should alert 'Plugin added later!' * ``` * * @param {String} The plugin name * @param {Function} The plugin function that will be called with options * @mixes videojs * @method plugin */ videojs.plugin = _plugin2['default']; /** * Adding languages so that they're available to all players. * ```js * videojs.addLanguage('es', { 'Hello': 'Hola' }); * ``` * * @param {String} code The language code or dictionary property * @param {Object} data The data values to be translated * @return {Object} The resulting language dictionary object * @mixes videojs * @method addLanguage */ videojs.addLanguage = function (code, data) { var _merge; code = ('' + code).toLowerCase(); return _merge3['default'](_globalOptions2['default'].languages, (_merge = {}, _merge[code] = data, _merge))[code]; }; /** * Log debug messages. * * @param {...Object} messages One or more messages to log */ videojs.log = _log2['default']; /** * Creates an emulated TimeRange object. * * @param {Number} start Start time in seconds * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @method createTimeRange */ videojs.createTimeRange = _createTimeRange.createTimeRange; /** * Simple http request for retrieving external files (e.g. text tracks) * * ##### Example * * // using url string * videojs.xhr('http://example.com/myfile.vtt', function(error, response, responseBody){}); * * // or options block * videojs.xhr({ * uri: 'http://example.com/myfile.vtt', * method: 'GET', * responseType: 'text' * }, function(error, response, responseBody){ * if (error) { * // log the error * } else { * // successful, do something with the response * } * }); * * * API is modeled after the Raynos/xhr. * https://github.com/Raynos/xhr/blob/master/index.js * * @param {Object|String} options Options block or URL string * @param {Function} callback The callback function * @returns {Object} The request */ videojs.xhr = _xhr2['default']; /** * Resolve and parse the elements of a URL * * @param {String} url The url to parse * @return {Object} An object of url details * @method parseUrl */ videojs.parseUrl = Url.parseUrl; /** * Event target class. * * @type {Function} */ videojs.EventTarget = _EventTarget2['default']; // REMOVING: We probably should add this to the migration plugin // // Expose but deprecate the window[componentName] method for accessing components // Object.getOwnPropertyNames(Component.components).forEach(function(name){ // let component = Component.components[name]; // // // A deprecation warning as the constuctor // module.exports[name] = function(player, options, ready){ // log.warn('Using videojs.'+name+' to access the '+name+' component has been deprecated. Please use videojs.getComponent("componentName")'); // // return new Component(player, options, ready); // }; // // // Allow the prototype and class methods to be accessible still this way // // Though anything that attempts to override class methods will no longer work // assign(module.exports[name], component); // }); /* * Custom Universal Module Definition (UMD) * * Video.js will never be a non-browser lib so we can simplify UMD a bunch and * still support requirejs and browserify. This also needs to be closure * compiler compatible, so string keys are used. */ if (typeof define === 'function' && define.amd) { define('videojs', [], function () { return videojs; }); // checking that module is an object too because of umdjs/umd#35 } else if (typeof exports === 'object' && typeof module === 'object') { module.exports = videojs; } exports['default'] = videojs; module.exports = exports['default']; },{"../../src/js/utils/merge-options.js":117,"./component":52,"./event-target":83,"./extends.js":84,"./global-options.js":86,"./player":92,"./plugins.js":93,"./setup":95,"./tech/flash.js":98,"./tech/html5.js":99,"./utils/browser.js":108,"./utils/create-deprecation-proxy.js":110,"./utils/dom.js":111,"./utils/fn.js":113,"./utils/log.js":116,"./utils/time-ranges.js":118,"./utils/url.js":120,"./xhr.js":122,"global/document":1,"lodash-compat/object/merge":40,"object.assign":44}],122:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file xhr.js */ var _import = _dereq_('./utils/url.js'); var Url = _interopRequireWildcard(_import); var _log = _dereq_('./utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _mergeOptions = _dereq_('./utils/merge-options.js'); var _mergeOptions2 = _interopRequireWildcard(_mergeOptions); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); /* * Simple http request for retrieving external files (e.g. text tracks) * ##### Example * // using url string * videojs.xhr('http://example.com/myfile.vtt', function(error, response, responseBody){}); * * // or options block * videojs.xhr({ * uri: 'http://example.com/myfile.vtt', * method: 'GET', * responseType: 'text' * }, function(error, response, responseBody){ * if (error) { * // log the error * } else { * // successful, do something with the response * } * }); * ///////////// * API is modeled after the Raynos/xhr, which we hope to use after * getting browserify implemented. * https://github.com/Raynos/xhr/blob/master/index.js * * @param {Object|String} options Options block or URL string * @param {Function} callback The callback function * @return {Object} The request * @method xhr */ var xhr = function xhr(options, callback) { var abortTimeout = undefined; // If options is a string it's the url if (typeof options === 'string') { options = { uri: options }; } // Merge with default options options = _mergeOptions2['default']({ method: 'GET', timeout: 45 * 1000 }, options); callback = callback || function () {}; var XHR = _window2['default'].XMLHttpRequest; if (typeof XHR === 'undefined') { // Shim XMLHttpRequest for older IEs XHR = function () { try { return new _window2['default'].ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e) {} try { return new _window2['default'].ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (f) {} try { return new _window2['default'].ActiveXObject('Msxml2.XMLHTTP'); } catch (g) {} throw new Error('This browser does not support XMLHttpRequest.'); }; } var request = new XHR(); // Store a reference to the url on the request instance request.uri = options.uri; var urlInfo = Url.parseUrl(options.uri); var winLoc = _window2['default'].location; var successHandler = function successHandler() { _window2['default'].clearTimeout(abortTimeout); callback(null, request, request.response || request.responseText); }; var errorHandler = function errorHandler(err) { _window2['default'].clearTimeout(abortTimeout); if (!err || typeof err === 'string') { err = new Error(err); } callback(err, request); }; // Check if url is for another domain/origin // IE8 doesn't know location.origin, so we won't rely on it here var crossOrigin = urlInfo.protocol + urlInfo.host !== winLoc.protocol + winLoc.host; // XDomainRequest -- Use for IE if XMLHTTPRequest2 isn't available // 'withCredentials' is only available in XMLHTTPRequest2 // Also XDomainRequest has a lot of gotchas, so only use if cross domain if (crossOrigin && _window2['default'].XDomainRequest && !('withCredentials' in request)) { request = new _window2['default'].XDomainRequest(); request.onload = successHandler; request.onerror = errorHandler; // These blank handlers need to be set to fix ie9 // http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/ request.onprogress = function () {}; request.ontimeout = function () {}; // XMLHTTPRequest } else { (function () { var fileUrl = urlInfo.protocol === 'file:' || winLoc.protocol === 'file:'; request.onreadystatechange = function () { if (request.readyState === 4) { if (request.timedout) { return errorHandler('timeout'); } if (request.status === 200 || fileUrl && request.status === 0) { successHandler(); } else { errorHandler(); } } }; if (options.timeout) { abortTimeout = _window2['default'].setTimeout(function () { if (request.readyState !== 4) { request.timedout = true; request.abort(); } }, options.timeout); } })(); } // open the connection try { // Third arg is async, or ignored by XDomainRequest request.open(options.method || 'GET', options.uri, true); } catch (err) { return errorHandler(err); } // withCredentials only supported by XMLHttpRequest2 if (options.withCredentials) { request.withCredentials = true; } if (options.responseType) { request.responseType = options.responseType; } // send the request try { request.send(); } catch (err) { return errorHandler(err); } return request; }; exports['default'] = xhr; module.exports = exports['default']; },{"./utils/log.js":116,"./utils/merge-options.js":117,"./utils/url.js":120,"global/window":2}]},{},[121])(121) }); //# sourceMappingURL=video.js.map /* vtt.js - v0.12.1 (https://github.com/mozilla/vtt.js) built on 08-07-2015 */ (function(root) { var vttjs = root.vttjs = {}; var cueShim = vttjs.VTTCue; var regionShim = vttjs.VTTRegion; var oldVTTCue = root.VTTCue; var oldVTTRegion = root.VTTRegion; vttjs.shim = function() { vttjs.VTTCue = cueShim; vttjs.VTTRegion = regionShim; }; vttjs.restore = function() { vttjs.VTTCue = oldVTTCue; vttjs.VTTRegion = oldVTTRegion; }; }(this)); /** * Copyright 2013 vtt.js Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(root, vttjs) { var autoKeyword = "auto"; var directionSetting = { "": true, "lr": true, "rl": true }; var alignSetting = { "start": true, "middle": true, "end": true, "left": true, "right": true }; function findDirectionSetting(value) { if (typeof value !== "string") { return false; } var dir = directionSetting[value.toLowerCase()]; return dir ? value.toLowerCase() : false; } function findAlignSetting(value) { if (typeof value !== "string") { return false; } var align = alignSetting[value.toLowerCase()]; return align ? value.toLowerCase() : false; } function extend(obj) { var i = 1; for (; i < arguments.length; i++) { var cobj = arguments[i]; for (var p in cobj) { obj[p] = cobj[p]; } } return obj; } function VTTCue(startTime, endTime, text) { var cue = this; var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var baseObj = {}; if (isIE8) { cue = document.createElement('custom'); } else { baseObj.enumerable = true; } /** * Shim implementation specific properties. These properties are not in * the spec. */ // Lets us know when the VTTCue's data has changed in such a way that we need // to recompute its display state. This lets us compute its display state // lazily. cue.hasBeenReset = false; /** * VTTCue and TextTrackCue properties * http://dev.w3.org/html5/webvtt/#vttcue-interface */ var _id = ""; var _pauseOnExit = false; var _startTime = startTime; var _endTime = endTime; var _text = text; var _region = null; var _vertical = ""; var _snapToLines = true; var _line = "auto"; var _lineAlign = "start"; var _position = 50; var _positionAlign = "middle"; var _size = 50; var _align = "middle"; Object.defineProperty(cue, "id", extend({}, baseObj, { get: function() { return _id; }, set: function(value) { _id = "" + value; } })); Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, { get: function() { return _pauseOnExit; }, set: function(value) { _pauseOnExit = !!value; } })); Object.defineProperty(cue, "startTime", extend({}, baseObj, { get: function() { return _startTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Start time must be set to a number."); } _startTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "endTime", extend({}, baseObj, { get: function() { return _endTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("End time must be set to a number."); } _endTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "text", extend({}, baseObj, { get: function() { return _text; }, set: function(value) { _text = "" + value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "region", extend({}, baseObj, { get: function() { return _region; }, set: function(value) { _region = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "vertical", extend({}, baseObj, { get: function() { return _vertical; }, set: function(value) { var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _vertical = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "snapToLines", extend({}, baseObj, { get: function() { return _snapToLines; }, set: function(value) { _snapToLines = !!value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "line", extend({}, baseObj, { get: function() { return _line; }, set: function(value) { if (typeof value !== "number" && value !== autoKeyword) { throw new SyntaxError("An invalid number or illegal string was specified."); } _line = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "lineAlign", extend({}, baseObj, { get: function() { return _lineAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _lineAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "position", extend({}, baseObj, { get: function() { return _position; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Position must be between 0 and 100."); } _position = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "positionAlign", extend({}, baseObj, { get: function() { return _positionAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _positionAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "size", extend({}, baseObj, { get: function() { return _size; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Size must be between 0 and 100."); } _size = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "align", extend({}, baseObj, { get: function() { return _align; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _align = setting; this.hasBeenReset = true; } })); /** * Other <track> spec defined properties */ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state cue.displayState = undefined; if (isIE8) { return cue; } } /** * VTTCue methods */ VTTCue.prototype.getCueAsHTML = function() { // Assume WebVTT.convertCueToDOMTree is on the global. return WebVTT.convertCueToDOMTree(window, this.text); }; root.VTTCue = root.VTTCue || VTTCue; vttjs.VTTCue = VTTCue; }(this, (this.vttjs || {}))); /** * Copyright 2013 vtt.js Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(root, vttjs) { var scrollSetting = { "": true, "up": true }; function findScrollSetting(value) { if (typeof value !== "string") { return false; } var scroll = scrollSetting[value.toLowerCase()]; return scroll ? value.toLowerCase() : false; } function isValidPercentValue(value) { return typeof value === "number" && (value >= 0 && value <= 100); } // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface function VTTRegion() { var _width = 100; var _lines = 3; var _regionAnchorX = 0; var _regionAnchorY = 100; var _viewportAnchorX = 0; var _viewportAnchorY = 100; var _scroll = ""; Object.defineProperties(this, { "width": { enumerable: true, get: function() { return _width; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("Width must be between 0 and 100."); } _width = value; } }, "lines": { enumerable: true, get: function() { return _lines; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Lines must be set to a number."); } _lines = value; } }, "regionAnchorY": { enumerable: true, get: function() { return _regionAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("RegionAnchorX must be between 0 and 100."); } _regionAnchorY = value; } }, "regionAnchorX": { enumerable: true, get: function() { return _regionAnchorX; }, set: function(value) { if(!isValidPercentValue(value)) { throw new Error("RegionAnchorY must be between 0 and 100."); } _regionAnchorX = value; } }, "viewportAnchorY": { enumerable: true, get: function() { return _viewportAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorY must be between 0 and 100."); } _viewportAnchorY = value; } }, "viewportAnchorX": { enumerable: true, get: function() { return _viewportAnchorX; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorX must be between 0 and 100."); } _viewportAnchorX = value; } }, "scroll": { enumerable: true, get: function() { return _scroll; }, set: function(value) { var setting = findScrollSetting(value); // Have to check for false as an empty string is a legal value. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _scroll = setting; } } }); } root.VTTRegion = root.VTTRegion || VTTRegion; vttjs.VTTRegion = VTTRegion; }(this, (this.vttjs || {}))); /** * Copyright 2013 vtt.js Contributors * * 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. */ /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ (function(global) { var _objCreate = Object.create || (function() { function F() {} return function(o) { if (arguments.length !== 1) { throw new Error('Object.create shim only accepts one parameter.'); } F.prototype = o; return new F(); }; })(); // Creates a new ParserError object from an errorData object. The errorData // object should have default code and message properties. The default message // property can be overriden by passing in a message parameter. // See ParsingError.Errors below for acceptable errors. function ParsingError(errorData, message) { this.name = "ParsingError"; this.code = errorData.code; this.message = message || errorData.message; } ParsingError.prototype = _objCreate(Error.prototype); ParsingError.prototype.constructor = ParsingError; // ParsingError metadata for acceptable ParsingErrors. ParsingError.Errors = { BadSignature: { code: 0, message: "Malformed WebVTT signature." }, BadTimeStamp: { code: 1, message: "Malformed time stamp." } }; // Try to parse input as a time stamp. function parseTimeStamp(input) { function computeSeconds(h, m, s, f) { return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000; } var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/); if (!m) { return null; } if (m[3]) { // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds] return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]); } else if (m[1] > 59) { // Timestamp takes the form of [hours]:[minutes].[milliseconds] // First position is hours as it's over 59. return computeSeconds(m[1], m[2], 0, m[4]); } else { // Timestamp takes the form of [minutes]:[seconds].[milliseconds] return computeSeconds(0, m[1], m[2], m[4]); } } // A settings object holds key/value pairs and will ignore anything but the first // assignment to a specific key. function Settings() { this.values = _objCreate(null); } Settings.prototype = { // Only accept the first assignment to any key. set: function(k, v) { if (!this.get(k) && v !== "") { this.values[k] = v; } }, // Return the value for a key, or a default value. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with // a number of possible default values as properties where 'defaultKey' is // the key of the property that will be chosen; otherwise it's assumed to be // a single value. get: function(k, dflt, defaultKey) { if (defaultKey) { return this.has(k) ? this.values[k] : dflt[defaultKey]; } return this.has(k) ? this.values[k] : dflt; }, // Check whether we have a value for a key. has: function(k) { return k in this.values; }, // Accept a setting if its one of the given alternatives. alt: function(k, v, a) { for (var n = 0; n < a.length; ++n) { if (v === a[n]) { this.set(k, v); break; } } }, // Accept a setting if its a valid (signed) integer. integer: function(k, v) { if (/^-?\d+$/.test(v)) { // integer this.set(k, parseInt(v, 10)); } }, // Accept a setting if its a valid percentage. percent: function(k, v) { var m; if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) { v = parseFloat(v); if (v >= 0 && v <= 100) { this.set(k, v); return true; } } return false; } }; // Helper function to parse input into groups separated by 'groupDelim', and // interprete each group as a key/value pair separated by 'keyValueDelim'. function parseOptions(input, callback, keyValueDelim, groupDelim) { var groups = groupDelim ? input.split(groupDelim) : [input]; for (var i in groups) { if (typeof groups[i] !== "string") { continue; } var kv = groups[i].split(keyValueDelim); if (kv.length !== 2) { continue; } var k = kv[0]; var v = kv[1]; callback(k, v); } } function parseCue(input, cue, regionList) { // Remember the original input if we need to throw an error. var oInput = input; // 4.1 WebVTT timestamp function consumeTimeStamp() { var ts = parseTimeStamp(input); if (ts === null) { throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput); } // Remove time stamp from input. input = input.replace(/^[^\sa-zA-Z-]+/, ""); return ts; } // 4.4.2 WebVTT cue settings function consumeCueSettings(input, cue) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "region": // Find the last region we parsed with the same region id. for (var i = regionList.length - 1; i >= 0; i--) { if (regionList[i].id === v) { settings.set(k, regionList[i].region); break; } } break; case "vertical": settings.alt(k, v, ["rl", "lr"]); break; case "line": var vals = v.split(","), vals0 = vals[0]; settings.integer(k, vals0); settings.percent(k, vals0) ? settings.set("snapToLines", false) : null; settings.alt(k, vals0, ["auto"]); if (vals.length === 2) { settings.alt("lineAlign", vals[1], ["start", "middle", "end"]); } break; case "position": vals = v.split(","); settings.percent(k, vals[0]); if (vals.length === 2) { settings.alt("positionAlign", vals[1], ["start", "middle", "end"]); } break; case "size": settings.percent(k, v); break; case "align": settings.alt(k, v, ["start", "middle", "end", "left", "right"]); break; } }, /:/, /\s/); // Apply default values for any missing fields. cue.region = settings.get("region", null); cue.vertical = settings.get("vertical", ""); cue.line = settings.get("line", "auto"); cue.lineAlign = settings.get("lineAlign", "start"); cue.snapToLines = settings.get("snapToLines", true); cue.size = settings.get("size", 100); cue.align = settings.get("align", "middle"); cue.position = settings.get("position", { start: 0, left: 0, middle: 50, end: 100, right: 100 }, cue.align); cue.positionAlign = settings.get("positionAlign", { start: "start", left: "start", middle: "middle", end: "end", right: "end" }, cue.align); } function skipWhitespace() { input = input.replace(/^\s+/, ""); } // 4.1 WebVTT cue timings. skipWhitespace(); cue.startTime = consumeTimeStamp(); // (1) collect cue start time skipWhitespace(); if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->" throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput); } input = input.substr(3); skipWhitespace(); cue.endTime = consumeTimeStamp(); // (5) collect cue end time // 4.1 WebVTT cue settings list. skipWhitespace(); consumeCueSettings(input, cue); } var ESCAPE = { "&amp;": "&", "&lt;": "<", "&gt;": ">", "&lrm;": "\u200e", "&rlm;": "\u200f", "&nbsp;": "\u00a0" }; var TAG_NAME = { c: "span", i: "i", b: "b", u: "u", ruby: "ruby", rt: "rt", v: "span", lang: "span" }; var TAG_ANNOTATION = { v: "title", lang: "lang" }; var NEEDS_PARENT = { rt: "ruby" }; // Parse content into a document fragment. function parseContent(window, input) { function nextToken() { // Check for end-of-string. if (!input) { return null; } // Consume 'n' characters from the input. function consume(result) { input = input.substr(result.length); return result; } var m = input.match(/^([^<]*)(<[^>]+>?)?/); // If there is some text before the next tag, return it, otherwise return // the tag. return consume(m[1] ? m[1] : m[2]); } // Unescape a string 's'. function unescape1(e) { return ESCAPE[e]; } function unescape(s) { while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) { s = s.replace(m[0], unescape1); } return s; } function shouldAdd(current, element) { return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName; } // Create an element for this tag. function createElement(type, annotation) { var tagName = TAG_NAME[type]; if (!tagName) { return null; } var element = window.document.createElement(tagName); element.localName = tagName; var name = TAG_ANNOTATION[type]; if (name && annotation) { element[name] = annotation.trim(); } return element; } var rootDiv = window.document.createElement("div"), current = rootDiv, t, tagStack = []; while ((t = nextToken()) !== null) { if (t[0] === '<') { if (t[1] === "/") { // If the closing tag matches, move back up to the parent node. if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) { tagStack.pop(); current = current.parentNode; } // Otherwise just ignore the end tag. continue; } var ts = parseTimeStamp(t.substr(1, t.length - 2)); var node; if (ts) { // Timestamps are lead nodes as well. node = window.document.createProcessingInstruction("timestamp", ts); current.appendChild(node); continue; } var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/); // If we can't parse the tag, skip to the next tag. if (!m) { continue; } // Try to construct an element, and ignore the tag if we couldn't. node = createElement(m[1], m[3]); if (!node) { continue; } // Determine if the tag should be added based on the context of where it // is placed in the cuetext. if (!shouldAdd(current, node)) { continue; } // Set the class list (as a list of classes, separated by space). if (m[2]) { node.className = m[2].substr(1).replace('.', ' '); } // Append the node to the current node, and enter the scope of the new // node. tagStack.push(m[1]); current.appendChild(node); current = node; continue; } // Text nodes are leaf nodes. current.appendChild(window.document.createTextNode(unescape(t))); } return rootDiv; } // This is a list of all the Unicode characters that have a strong // right-to-left category. What this means is that these characters are // written right-to-left for sure. It was generated by pulling all the strong // right-to-left characters out of the Unicode data table. That table can // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt var strongRTLChars = [0x05BE, 0x05C0, 0x05C3, 0x05C6, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0x0608, 0x060B, 0x060D, 0x061B, 0x061E, 0x061F, 0x0620, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637, 0x0638, 0x0639, 0x063A, 0x063B, 0x063C, 0x063D, 0x063E, 0x063F, 0x0640, 0x0641, 0x0642, 0x0643, 0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A, 0x066D, 0x066E, 0x066F, 0x0671, 0x0672, 0x0673, 0x0674, 0x0675, 0x0676, 0x0677, 0x0678, 0x0679, 0x067A, 0x067B, 0x067C, 0x067D, 0x067E, 0x067F, 0x0680, 0x0681, 0x0682, 0x0683, 0x0684, 0x0685, 0x0686, 0x0687, 0x0688, 0x0689, 0x068A, 0x068B, 0x068C, 0x068D, 0x068E, 0x068F, 0x0690, 0x0691, 0x0692, 0x0693, 0x0694, 0x0695, 0x0696, 0x0697, 0x0698, 0x0699, 0x069A, 0x069B, 0x069C, 0x069D, 0x069E, 0x069F, 0x06A0, 0x06A1, 0x06A2, 0x06A3, 0x06A4, 0x06A5, 0x06A6, 0x06A7, 0x06A8, 0x06A9, 0x06AA, 0x06AB, 0x06AC, 0x06AD, 0x06AE, 0x06AF, 0x06B0, 0x06B1, 0x06B2, 0x06B3, 0x06B4, 0x06B5, 0x06B6, 0x06B7, 0x06B8, 0x06B9, 0x06BA, 0x06BB, 0x06BC, 0x06BD, 0x06BE, 0x06BF, 0x06C0, 0x06C1, 0x06C2, 0x06C3, 0x06C4, 0x06C5, 0x06C6, 0x06C7, 0x06C8, 0x06C9, 0x06CA, 0x06CB, 0x06CC, 0x06CD, 0x06CE, 0x06CF, 0x06D0, 0x06D1, 0x06D2, 0x06D3, 0x06D4, 0x06D5, 0x06E5, 0x06E6, 0x06EE, 0x06EF, 0x06FA, 0x06FB, 0x06FC, 0x06FD, 0x06FE, 0x06FF, 0x0700, 0x0701, 0x0702, 0x0703, 0x0704, 0x0705, 0x0706, 0x0707, 0x0708, 0x0709, 0x070A, 0x070B, 0x070C, 0x070D, 0x070F, 0x0710, 0x0712, 0x0713, 0x0714, 0x0715, 0x0716, 0x0717, 0x0718, 0x0719, 0x071A, 0x071B, 0x071C, 0x071D, 0x071E, 0x071F, 0x0720, 0x0721, 0x0722, 0x0723, 0x0724, 0x0725, 0x0726, 0x0727, 0x0728, 0x0729, 0x072A, 0x072B, 0x072C, 0x072D, 0x072E, 0x072F, 0x074D, 0x074E, 0x074F, 0x0750, 0x0751, 0x0752, 0x0753, 0x0754, 0x0755, 0x0756, 0x0757, 0x0758, 0x0759, 0x075A, 0x075B, 0x075C, 0x075D, 0x075E, 0x075F, 0x0760, 0x0761, 0x0762, 0x0763, 0x0764, 0x0765, 0x0766, 0x0767, 0x0768, 0x0769, 0x076A, 0x076B, 0x076C, 0x076D, 0x076E, 0x076F, 0x0770, 0x0771, 0x0772, 0x0773, 0x0774, 0x0775, 0x0776, 0x0777, 0x0778, 0x0779, 0x077A, 0x077B, 0x077C, 0x077D, 0x077E, 0x077F, 0x0780, 0x0781, 0x0782, 0x0783, 0x0784, 0x0785, 0x0786, 0x0787, 0x0788, 0x0789, 0x078A, 0x078B, 0x078C, 0x078D, 0x078E, 0x078F, 0x0790, 0x0791, 0x0792, 0x0793, 0x0794, 0x0795, 0x0796, 0x0797, 0x0798, 0x0799, 0x079A, 0x079B, 0x079C, 0x079D, 0x079E, 0x079F, 0x07A0, 0x07A1, 0x07A2, 0x07A3, 0x07A4, 0x07A5, 0x07B1, 0x07C0, 0x07C1, 0x07C2, 0x07C3, 0x07C4, 0x07C5, 0x07C6, 0x07C7, 0x07C8, 0x07C9, 0x07CA, 0x07CB, 0x07CC, 0x07CD, 0x07CE, 0x07CF, 0x07D0, 0x07D1, 0x07D2, 0x07D3, 0x07D4, 0x07D5, 0x07D6, 0x07D7, 0x07D8, 0x07D9, 0x07DA, 0x07DB, 0x07DC, 0x07DD, 0x07DE, 0x07DF, 0x07E0, 0x07E1, 0x07E2, 0x07E3, 0x07E4, 0x07E5, 0x07E6, 0x07E7, 0x07E8, 0x07E9, 0x07EA, 0x07F4, 0x07F5, 0x07FA, 0x0800, 0x0801, 0x0802, 0x0803, 0x0804, 0x0805, 0x0806, 0x0807, 0x0808, 0x0809, 0x080A, 0x080B, 0x080C, 0x080D, 0x080E, 0x080F, 0x0810, 0x0811, 0x0812, 0x0813, 0x0814, 0x0815, 0x081A, 0x0824, 0x0828, 0x0830, 0x0831, 0x0832, 0x0833, 0x0834, 0x0835, 0x0836, 0x0837, 0x0838, 0x0839, 0x083A, 0x083B, 0x083C, 0x083D, 0x083E, 0x0840, 0x0841, 0x0842, 0x0843, 0x0844, 0x0845, 0x0846, 0x0847, 0x0848, 0x0849, 0x084A, 0x084B, 0x084C, 0x084D, 0x084E, 0x084F, 0x0850, 0x0851, 0x0852, 0x0853, 0x0854, 0x0855, 0x0856, 0x0857, 0x0858, 0x085E, 0x08A0, 0x08A2, 0x08A3, 0x08A4, 0x08A5, 0x08A6, 0x08A7, 0x08A8, 0x08A9, 0x08AA, 0x08AB, 0x08AC, 0x200F, 0xFB1D, 0xFB1F, 0xFB20, 0xFB21, 0xFB22, 0xFB23, 0xFB24, 0xFB25, 0xFB26, 0xFB27, 0xFB28, 0xFB2A, 0xFB2B, 0xFB2C, 0xFB2D, 0xFB2E, 0xFB2F, 0xFB30, 0xFB31, 0xFB32, 0xFB33, 0xFB34, 0xFB35, 0xFB36, 0xFB38, 0xFB39, 0xFB3A, 0xFB3B, 0xFB3C, 0xFB3E, 0xFB40, 0xFB41, 0xFB43, 0xFB44, 0xFB46, 0xFB47, 0xFB48, 0xFB49, 0xFB4A, 0xFB4B, 0xFB4C, 0xFB4D, 0xFB4E, 0xFB4F, 0xFB50, 0xFB51, 0xFB52, 0xFB53, 0xFB54, 0xFB55, 0xFB56, 0xFB57, 0xFB58, 0xFB59, 0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D, 0xFB5E, 0xFB5F, 0xFB60, 0xFB61, 0xFB62, 0xFB63, 0xFB64, 0xFB65, 0xFB66, 0xFB67, 0xFB68, 0xFB69, 0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D, 0xFB6E, 0xFB6F, 0xFB70, 0xFB71, 0xFB72, 0xFB73, 0xFB74, 0xFB75, 0xFB76, 0xFB77, 0xFB78, 0xFB79, 0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D, 0xFB7E, 0xFB7F, 0xFB80, 0xFB81, 0xFB82, 0xFB83, 0xFB84, 0xFB85, 0xFB86, 0xFB87, 0xFB88, 0xFB89, 0xFB8A, 0xFB8B, 0xFB8C, 0xFB8D, 0xFB8E, 0xFB8F, 0xFB90, 0xFB91, 0xFB92, 0xFB93, 0xFB94, 0xFB95, 0xFB96, 0xFB97, 0xFB98, 0xFB99, 0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D, 0xFB9E, 0xFB9F, 0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3, 0xFBA4, 0xFBA5, 0xFBA6, 0xFBA7, 0xFBA8, 0xFBA9, 0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD, 0xFBAE, 0xFBAF, 0xFBB0, 0xFBB1, 0xFBB2, 0xFBB3, 0xFBB4, 0xFBB5, 0xFBB6, 0xFBB7, 0xFBB8, 0xFBB9, 0xFBBA, 0xFBBB, 0xFBBC, 0xFBBD, 0xFBBE, 0xFBBF, 0xFBC0, 0xFBC1, 0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6, 0xFBD7, 0xFBD8, 0xFBD9, 0xFBDA, 0xFBDB, 0xFBDC, 0xFBDD, 0xFBDE, 0xFBDF, 0xFBE0, 0xFBE1, 0xFBE2, 0xFBE3, 0xFBE4, 0xFBE5, 0xFBE6, 0xFBE7, 0xFBE8, 0xFBE9, 0xFBEA, 0xFBEB, 0xFBEC, 0xFBED, 0xFBEE, 0xFBEF, 0xFBF0, 0xFBF1, 0xFBF2, 0xFBF3, 0xFBF4, 0xFBF5, 0xFBF6, 0xFBF7, 0xFBF8, 0xFBF9, 0xFBFA, 0xFBFB, 0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF, 0xFC00, 0xFC01, 0xFC02, 0xFC03, 0xFC04, 0xFC05, 0xFC06, 0xFC07, 0xFC08, 0xFC09, 0xFC0A, 0xFC0B, 0xFC0C, 0xFC0D, 0xFC0E, 0xFC0F, 0xFC10, 0xFC11, 0xFC12, 0xFC13, 0xFC14, 0xFC15, 0xFC16, 0xFC17, 0xFC18, 0xFC19, 0xFC1A, 0xFC1B, 0xFC1C, 0xFC1D, 0xFC1E, 0xFC1F, 0xFC20, 0xFC21, 0xFC22, 0xFC23, 0xFC24, 0xFC25, 0xFC26, 0xFC27, 0xFC28, 0xFC29, 0xFC2A, 0xFC2B, 0xFC2C, 0xFC2D, 0xFC2E, 0xFC2F, 0xFC30, 0xFC31, 0xFC32, 0xFC33, 0xFC34, 0xFC35, 0xFC36, 0xFC37, 0xFC38, 0xFC39, 0xFC3A, 0xFC3B, 0xFC3C, 0xFC3D, 0xFC3E, 0xFC3F, 0xFC40, 0xFC41, 0xFC42, 0xFC43, 0xFC44, 0xFC45, 0xFC46, 0xFC47, 0xFC48, 0xFC49, 0xFC4A, 0xFC4B, 0xFC4C, 0xFC4D, 0xFC4E, 0xFC4F, 0xFC50, 0xFC51, 0xFC52, 0xFC53, 0xFC54, 0xFC55, 0xFC56, 0xFC57, 0xFC58, 0xFC59, 0xFC5A, 0xFC5B, 0xFC5C, 0xFC5D, 0xFC5E, 0xFC5F, 0xFC60, 0xFC61, 0xFC62, 0xFC63, 0xFC64, 0xFC65, 0xFC66, 0xFC67, 0xFC68, 0xFC69, 0xFC6A, 0xFC6B, 0xFC6C, 0xFC6D, 0xFC6E, 0xFC6F, 0xFC70, 0xFC71, 0xFC72, 0xFC73, 0xFC74, 0xFC75, 0xFC76, 0xFC77, 0xFC78, 0xFC79, 0xFC7A, 0xFC7B, 0xFC7C, 0xFC7D, 0xFC7E, 0xFC7F, 0xFC80, 0xFC81, 0xFC82, 0xFC83, 0xFC84, 0xFC85, 0xFC86, 0xFC87, 0xFC88, 0xFC89, 0xFC8A, 0xFC8B, 0xFC8C, 0xFC8D, 0xFC8E, 0xFC8F, 0xFC90, 0xFC91, 0xFC92, 0xFC93, 0xFC94, 0xFC95, 0xFC96, 0xFC97, 0xFC98, 0xFC99, 0xFC9A, 0xFC9B, 0xFC9C, 0xFC9D, 0xFC9E, 0xFC9F, 0xFCA0, 0xFCA1, 0xFCA2, 0xFCA3, 0xFCA4, 0xFCA5, 0xFCA6, 0xFCA7, 0xFCA8, 0xFCA9, 0xFCAA, 0xFCAB, 0xFCAC, 0xFCAD, 0xFCAE, 0xFCAF, 0xFCB0, 0xFCB1, 0xFCB2, 0xFCB3, 0xFCB4, 0xFCB5, 0xFCB6, 0xFCB7, 0xFCB8, 0xFCB9, 0xFCBA, 0xFCBB, 0xFCBC, 0xFCBD, 0xFCBE, 0xFCBF, 0xFCC0, 0xFCC1, 0xFCC2, 0xFCC3, 0xFCC4, 0xFCC5, 0xFCC6, 0xFCC7, 0xFCC8, 0xFCC9, 0xFCCA, 0xFCCB, 0xFCCC, 0xFCCD, 0xFCCE, 0xFCCF, 0xFCD0, 0xFCD1, 0xFCD2, 0xFCD3, 0xFCD4, 0xFCD5, 0xFCD6, 0xFCD7, 0xFCD8, 0xFCD9, 0xFCDA, 0xFCDB, 0xFCDC, 0xFCDD, 0xFCDE, 0xFCDF, 0xFCE0, 0xFCE1, 0xFCE2, 0xFCE3, 0xFCE4, 0xFCE5, 0xFCE6, 0xFCE7, 0xFCE8, 0xFCE9, 0xFCEA, 0xFCEB, 0xFCEC, 0xFCED, 0xFCEE, 0xFCEF, 0xFCF0, 0xFCF1, 0xFCF2, 0xFCF3, 0xFCF4, 0xFCF5, 0xFCF6, 0xFCF7, 0xFCF8, 0xFCF9, 0xFCFA, 0xFCFB, 0xFCFC, 0xFCFD, 0xFCFE, 0xFCFF, 0xFD00, 0xFD01, 0xFD02, 0xFD03, 0xFD04, 0xFD05, 0xFD06, 0xFD07, 0xFD08, 0xFD09, 0xFD0A, 0xFD0B, 0xFD0C, 0xFD0D, 0xFD0E, 0xFD0F, 0xFD10, 0xFD11, 0xFD12, 0xFD13, 0xFD14, 0xFD15, 0xFD16, 0xFD17, 0xFD18, 0xFD19, 0xFD1A, 0xFD1B, 0xFD1C, 0xFD1D, 0xFD1E, 0xFD1F, 0xFD20, 0xFD21, 0xFD22, 0xFD23, 0xFD24, 0xFD25, 0xFD26, 0xFD27, 0xFD28, 0xFD29, 0xFD2A, 0xFD2B, 0xFD2C, 0xFD2D, 0xFD2E, 0xFD2F, 0xFD30, 0xFD31, 0xFD32, 0xFD33, 0xFD34, 0xFD35, 0xFD36, 0xFD37, 0xFD38, 0xFD39, 0xFD3A, 0xFD3B, 0xFD3C, 0xFD3D, 0xFD50, 0xFD51, 0xFD52, 0xFD53, 0xFD54, 0xFD55, 0xFD56, 0xFD57, 0xFD58, 0xFD59, 0xFD5A, 0xFD5B, 0xFD5C, 0xFD5D, 0xFD5E, 0xFD5F, 0xFD60, 0xFD61, 0xFD62, 0xFD63, 0xFD64, 0xFD65, 0xFD66, 0xFD67, 0xFD68, 0xFD69, 0xFD6A, 0xFD6B, 0xFD6C, 0xFD6D, 0xFD6E, 0xFD6F, 0xFD70, 0xFD71, 0xFD72, 0xFD73, 0xFD74, 0xFD75, 0xFD76, 0xFD77, 0xFD78, 0xFD79, 0xFD7A, 0xFD7B, 0xFD7C, 0xFD7D, 0xFD7E, 0xFD7F, 0xFD80, 0xFD81, 0xFD82, 0xFD83, 0xFD84, 0xFD85, 0xFD86, 0xFD87, 0xFD88, 0xFD89, 0xFD8A, 0xFD8B, 0xFD8C, 0xFD8D, 0xFD8E, 0xFD8F, 0xFD92, 0xFD93, 0xFD94, 0xFD95, 0xFD96, 0xFD97, 0xFD98, 0xFD99, 0xFD9A, 0xFD9B, 0xFD9C, 0xFD9D, 0xFD9E, 0xFD9F, 0xFDA0, 0xFDA1, 0xFDA2, 0xFDA3, 0xFDA4, 0xFDA5, 0xFDA6, 0xFDA7, 0xFDA8, 0xFDA9, 0xFDAA, 0xFDAB, 0xFDAC, 0xFDAD, 0xFDAE, 0xFDAF, 0xFDB0, 0xFDB1, 0xFDB2, 0xFDB3, 0xFDB4, 0xFDB5, 0xFDB6, 0xFDB7, 0xFDB8, 0xFDB9, 0xFDBA, 0xFDBB, 0xFDBC, 0xFDBD, 0xFDBE, 0xFDBF, 0xFDC0, 0xFDC1, 0xFDC2, 0xFDC3, 0xFDC4, 0xFDC5, 0xFDC6, 0xFDC7, 0xFDF0, 0xFDF1, 0xFDF2, 0xFDF3, 0xFDF4, 0xFDF5, 0xFDF6, 0xFDF7, 0xFDF8, 0xFDF9, 0xFDFA, 0xFDFB, 0xFDFC, 0xFE70, 0xFE71, 0xFE72, 0xFE73, 0xFE74, 0xFE76, 0xFE77, 0xFE78, 0xFE79, 0xFE7A, 0xFE7B, 0xFE7C, 0xFE7D, 0xFE7E, 0xFE7F, 0xFE80, 0xFE81, 0xFE82, 0xFE83, 0xFE84, 0xFE85, 0xFE86, 0xFE87, 0xFE88, 0xFE89, 0xFE8A, 0xFE8B, 0xFE8C, 0xFE8D, 0xFE8E, 0xFE8F, 0xFE90, 0xFE91, 0xFE92, 0xFE93, 0xFE94, 0xFE95, 0xFE96, 0xFE97, 0xFE98, 0xFE99, 0xFE9A, 0xFE9B, 0xFE9C, 0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0, 0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4, 0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8, 0xFEA9, 0xFEAA, 0xFEAB, 0xFEAC, 0xFEAD, 0xFEAE, 0xFEAF, 0xFEB0, 0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4, 0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8, 0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC, 0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0, 0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4, 0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8, 0xFEC9, 0xFECA, 0xFECB, 0xFECC, 0xFECD, 0xFECE, 0xFECF, 0xFED0, 0xFED1, 0xFED2, 0xFED3, 0xFED4, 0xFED5, 0xFED6, 0xFED7, 0xFED8, 0xFED9, 0xFEDA, 0xFEDB, 0xFEDC, 0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0, 0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4, 0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8, 0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC, 0xFEED, 0xFEEE, 0xFEEF, 0xFEF0, 0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4, 0xFEF5, 0xFEF6, 0xFEF7, 0xFEF8, 0xFEF9, 0xFEFA, 0xFEFB, 0xFEFC, 0x10800, 0x10801, 0x10802, 0x10803, 0x10804, 0x10805, 0x10808, 0x1080A, 0x1080B, 0x1080C, 0x1080D, 0x1080E, 0x1080F, 0x10810, 0x10811, 0x10812, 0x10813, 0x10814, 0x10815, 0x10816, 0x10817, 0x10818, 0x10819, 0x1081A, 0x1081B, 0x1081C, 0x1081D, 0x1081E, 0x1081F, 0x10820, 0x10821, 0x10822, 0x10823, 0x10824, 0x10825, 0x10826, 0x10827, 0x10828, 0x10829, 0x1082A, 0x1082B, 0x1082C, 0x1082D, 0x1082E, 0x1082F, 0x10830, 0x10831, 0x10832, 0x10833, 0x10834, 0x10835, 0x10837, 0x10838, 0x1083C, 0x1083F, 0x10840, 0x10841, 0x10842, 0x10843, 0x10844, 0x10845, 0x10846, 0x10847, 0x10848, 0x10849, 0x1084A, 0x1084B, 0x1084C, 0x1084D, 0x1084E, 0x1084F, 0x10850, 0x10851, 0x10852, 0x10853, 0x10854, 0x10855, 0x10857, 0x10858, 0x10859, 0x1085A, 0x1085B, 0x1085C, 0x1085D, 0x1085E, 0x1085F, 0x10900, 0x10901, 0x10902, 0x10903, 0x10904, 0x10905, 0x10906, 0x10907, 0x10908, 0x10909, 0x1090A, 0x1090B, 0x1090C, 0x1090D, 0x1090E, 0x1090F, 0x10910, 0x10911, 0x10912, 0x10913, 0x10914, 0x10915, 0x10916, 0x10917, 0x10918, 0x10919, 0x1091A, 0x1091B, 0x10920, 0x10921, 0x10922, 0x10923, 0x10924, 0x10925, 0x10926, 0x10927, 0x10928, 0x10929, 0x1092A, 0x1092B, 0x1092C, 0x1092D, 0x1092E, 0x1092F, 0x10930, 0x10931, 0x10932, 0x10933, 0x10934, 0x10935, 0x10936, 0x10937, 0x10938, 0x10939, 0x1093F, 0x10980, 0x10981, 0x10982, 0x10983, 0x10984, 0x10985, 0x10986, 0x10987, 0x10988, 0x10989, 0x1098A, 0x1098B, 0x1098C, 0x1098D, 0x1098E, 0x1098F, 0x10990, 0x10991, 0x10992, 0x10993, 0x10994, 0x10995, 0x10996, 0x10997, 0x10998, 0x10999, 0x1099A, 0x1099B, 0x1099C, 0x1099D, 0x1099E, 0x1099F, 0x109A0, 0x109A1, 0x109A2, 0x109A3, 0x109A4, 0x109A5, 0x109A6, 0x109A7, 0x109A8, 0x109A9, 0x109AA, 0x109AB, 0x109AC, 0x109AD, 0x109AE, 0x109AF, 0x109B0, 0x109B1, 0x109B2, 0x109B3, 0x109B4, 0x109B5, 0x109B6, 0x109B7, 0x109BE, 0x109BF, 0x10A00, 0x10A10, 0x10A11, 0x10A12, 0x10A13, 0x10A15, 0x10A16, 0x10A17, 0x10A19, 0x10A1A, 0x10A1B, 0x10A1C, 0x10A1D, 0x10A1E, 0x10A1F, 0x10A20, 0x10A21, 0x10A22, 0x10A23, 0x10A24, 0x10A25, 0x10A26, 0x10A27, 0x10A28, 0x10A29, 0x10A2A, 0x10A2B, 0x10A2C, 0x10A2D, 0x10A2E, 0x10A2F, 0x10A30, 0x10A31, 0x10A32, 0x10A33, 0x10A40, 0x10A41, 0x10A42, 0x10A43, 0x10A44, 0x10A45, 0x10A46, 0x10A47, 0x10A50, 0x10A51, 0x10A52, 0x10A53, 0x10A54, 0x10A55, 0x10A56, 0x10A57, 0x10A58, 0x10A60, 0x10A61, 0x10A62, 0x10A63, 0x10A64, 0x10A65, 0x10A66, 0x10A67, 0x10A68, 0x10A69, 0x10A6A, 0x10A6B, 0x10A6C, 0x10A6D, 0x10A6E, 0x10A6F, 0x10A70, 0x10A71, 0x10A72, 0x10A73, 0x10A74, 0x10A75, 0x10A76, 0x10A77, 0x10A78, 0x10A79, 0x10A7A, 0x10A7B, 0x10A7C, 0x10A7D, 0x10A7E, 0x10A7F, 0x10B00, 0x10B01, 0x10B02, 0x10B03, 0x10B04, 0x10B05, 0x10B06, 0x10B07, 0x10B08, 0x10B09, 0x10B0A, 0x10B0B, 0x10B0C, 0x10B0D, 0x10B0E, 0x10B0F, 0x10B10, 0x10B11, 0x10B12, 0x10B13, 0x10B14, 0x10B15, 0x10B16, 0x10B17, 0x10B18, 0x10B19, 0x10B1A, 0x10B1B, 0x10B1C, 0x10B1D, 0x10B1E, 0x10B1F, 0x10B20, 0x10B21, 0x10B22, 0x10B23, 0x10B24, 0x10B25, 0x10B26, 0x10B27, 0x10B28, 0x10B29, 0x10B2A, 0x10B2B, 0x10B2C, 0x10B2D, 0x10B2E, 0x10B2F, 0x10B30, 0x10B31, 0x10B32, 0x10B33, 0x10B34, 0x10B35, 0x10B40, 0x10B41, 0x10B42, 0x10B43, 0x10B44, 0x10B45, 0x10B46, 0x10B47, 0x10B48, 0x10B49, 0x10B4A, 0x10B4B, 0x10B4C, 0x10B4D, 0x10B4E, 0x10B4F, 0x10B50, 0x10B51, 0x10B52, 0x10B53, 0x10B54, 0x10B55, 0x10B58, 0x10B59, 0x10B5A, 0x10B5B, 0x10B5C, 0x10B5D, 0x10B5E, 0x10B5F, 0x10B60, 0x10B61, 0x10B62, 0x10B63, 0x10B64, 0x10B65, 0x10B66, 0x10B67, 0x10B68, 0x10B69, 0x10B6A, 0x10B6B, 0x10B6C, 0x10B6D, 0x10B6E, 0x10B6F, 0x10B70, 0x10B71, 0x10B72, 0x10B78, 0x10B79, 0x10B7A, 0x10B7B, 0x10B7C, 0x10B7D, 0x10B7E, 0x10B7F, 0x10C00, 0x10C01, 0x10C02, 0x10C03, 0x10C04, 0x10C05, 0x10C06, 0x10C07, 0x10C08, 0x10C09, 0x10C0A, 0x10C0B, 0x10C0C, 0x10C0D, 0x10C0E, 0x10C0F, 0x10C10, 0x10C11, 0x10C12, 0x10C13, 0x10C14, 0x10C15, 0x10C16, 0x10C17, 0x10C18, 0x10C19, 0x10C1A, 0x10C1B, 0x10C1C, 0x10C1D, 0x10C1E, 0x10C1F, 0x10C20, 0x10C21, 0x10C22, 0x10C23, 0x10C24, 0x10C25, 0x10C26, 0x10C27, 0x10C28, 0x10C29, 0x10C2A, 0x10C2B, 0x10C2C, 0x10C2D, 0x10C2E, 0x10C2F, 0x10C30, 0x10C31, 0x10C32, 0x10C33, 0x10C34, 0x10C35, 0x10C36, 0x10C37, 0x10C38, 0x10C39, 0x10C3A, 0x10C3B, 0x10C3C, 0x10C3D, 0x10C3E, 0x10C3F, 0x10C40, 0x10C41, 0x10C42, 0x10C43, 0x10C44, 0x10C45, 0x10C46, 0x10C47, 0x10C48, 0x1EE00, 0x1EE01, 0x1EE02, 0x1EE03, 0x1EE05, 0x1EE06, 0x1EE07, 0x1EE08, 0x1EE09, 0x1EE0A, 0x1EE0B, 0x1EE0C, 0x1EE0D, 0x1EE0E, 0x1EE0F, 0x1EE10, 0x1EE11, 0x1EE12, 0x1EE13, 0x1EE14, 0x1EE15, 0x1EE16, 0x1EE17, 0x1EE18, 0x1EE19, 0x1EE1A, 0x1EE1B, 0x1EE1C, 0x1EE1D, 0x1EE1E, 0x1EE1F, 0x1EE21, 0x1EE22, 0x1EE24, 0x1EE27, 0x1EE29, 0x1EE2A, 0x1EE2B, 0x1EE2C, 0x1EE2D, 0x1EE2E, 0x1EE2F, 0x1EE30, 0x1EE31, 0x1EE32, 0x1EE34, 0x1EE35, 0x1EE36, 0x1EE37, 0x1EE39, 0x1EE3B, 0x1EE42, 0x1EE47, 0x1EE49, 0x1EE4B, 0x1EE4D, 0x1EE4E, 0x1EE4F, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE57, 0x1EE59, 0x1EE5B, 0x1EE5D, 0x1EE5F, 0x1EE61, 0x1EE62, 0x1EE64, 0x1EE67, 0x1EE68, 0x1EE69, 0x1EE6A, 0x1EE6C, 0x1EE6D, 0x1EE6E, 0x1EE6F, 0x1EE70, 0x1EE71, 0x1EE72, 0x1EE74, 0x1EE75, 0x1EE76, 0x1EE77, 0x1EE79, 0x1EE7A, 0x1EE7B, 0x1EE7C, 0x1EE7E, 0x1EE80, 0x1EE81, 0x1EE82, 0x1EE83, 0x1EE84, 0x1EE85, 0x1EE86, 0x1EE87, 0x1EE88, 0x1EE89, 0x1EE8B, 0x1EE8C, 0x1EE8D, 0x1EE8E, 0x1EE8F, 0x1EE90, 0x1EE91, 0x1EE92, 0x1EE93, 0x1EE94, 0x1EE95, 0x1EE96, 0x1EE97, 0x1EE98, 0x1EE99, 0x1EE9A, 0x1EE9B, 0x1EEA1, 0x1EEA2, 0x1EEA3, 0x1EEA5, 0x1EEA6, 0x1EEA7, 0x1EEA8, 0x1EEA9, 0x1EEAB, 0x1EEAC, 0x1EEAD, 0x1EEAE, 0x1EEAF, 0x1EEB0, 0x1EEB1, 0x1EEB2, 0x1EEB3, 0x1EEB4, 0x1EEB5, 0x1EEB6, 0x1EEB7, 0x1EEB8, 0x1EEB9, 0x1EEBA, 0x1EEBB, 0x10FFFD]; function determineBidi(cueDiv) { var nodeStack = [], text = "", charCode; if (!cueDiv || !cueDiv.childNodes) { return "ltr"; } function pushNodes(nodeStack, node) { for (var i = node.childNodes.length - 1; i >= 0; i--) { nodeStack.push(node.childNodes[i]); } } function nextTextNode(nodeStack) { if (!nodeStack || !nodeStack.length) { return null; } var node = nodeStack.pop(), text = node.textContent || node.innerText; if (text) { // TODO: This should match all unicode type B characters (paragraph // separator characters). See issue #115. var m = text.match(/^.*(\n|\r)/); if (m) { nodeStack.length = 0; return m[0]; } return text; } if (node.tagName === "ruby") { return nextTextNode(nodeStack); } if (node.childNodes) { pushNodes(nodeStack, node); return nextTextNode(nodeStack); } } pushNodes(nodeStack, cueDiv); while ((text = nextTextNode(nodeStack))) { for (var i = 0; i < text.length; i++) { charCode = text.charCodeAt(i); for (var j = 0; j < strongRTLChars.length; j++) { if (strongRTLChars[j] === charCode) { return "rtl"; } } } } return "ltr"; } function computeLinePos(cue) { if (typeof cue.line === "number" && (cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) { return cue.line; } if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) { return -1; } var track = cue.track, trackList = track.textTrackList, count = 0; for (var i = 0; i < trackList.length && trackList[i] !== track; i++) { if (trackList[i].mode === "showing") { count++; } } return ++count * -1; } function StyleBox() { } // Apply styles to a div. If there is no div passed then it defaults to the // div on 'this'. StyleBox.prototype.applyStyles = function(styles, div) { div = div || this.div; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { div.style[prop] = styles[prop]; } } }; StyleBox.prototype.formatStyle = function(val, unit) { return val === 0 ? 0 : val + unit; }; // Constructs the computed display state of the cue (a div). Places the div // into the overlay which should be a block level element (usually a div). function CueStyleBox(window, cue, styleOptions) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var color = "rgba(255, 255, 255, 1)"; var backgroundColor = "rgba(0, 0, 0, 0.8)"; if (isIE8) { color = "rgb(255, 255, 255)"; backgroundColor = "rgb(0, 0, 0)"; } StyleBox.call(this); this.cue = cue; // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will // have inline positioning and will function as the cue background box. this.cueDiv = parseContent(window, cue.text); var styles = { color: color, backgroundColor: backgroundColor, position: "relative", left: 0, right: 0, top: 0, bottom: 0, display: "inline" }; if (!isIE8) { styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl"; styles.unicodeBidi = "plaintext"; } this.applyStyles(styles, this.cueDiv); // Create an absolutely positioned div that will be used to position the cue // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS // mirrors of them except "middle" which is "center" in CSS. this.div = window.document.createElement("div"); styles = { textAlign: cue.align === "middle" ? "center" : cue.align, font: styleOptions.font, whiteSpace: "pre-line", position: "absolute" }; if (!isIE8) { styles.direction = determineBidi(this.cueDiv); styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl". stylesunicodeBidi = "plaintext"; } this.applyStyles(styles); this.div.appendChild(this.cueDiv); // Calculate the distance from the reference edge of the viewport to the text // position of the cue box. The reference edge will be resolved later when // the box orientation styles are applied. var textPos = 0; switch (cue.positionAlign) { case "start": textPos = cue.position; break; case "middle": textPos = cue.position - (cue.size / 2); break; case "end": textPos = cue.position - cue.size; break; } // Horizontal box orientation; textPos is the distance from the left edge of the // area to the left edge of the box and cue.size is the distance extending to // the right from there. if (cue.vertical === "") { this.applyStyles({ left: this.formatStyle(textPos, "%"), width: this.formatStyle(cue.size, "%") }); // Vertical box orientation; textPos is the distance from the top edge of the // area to the top edge of the box and cue.size is the height extending // downwards from there. } else { this.applyStyles({ top: this.formatStyle(textPos, "%"), height: this.formatStyle(cue.size, "%") }); } this.move = function(box) { this.applyStyles({ top: this.formatStyle(box.top, "px"), bottom: this.formatStyle(box.bottom, "px"), left: this.formatStyle(box.left, "px"), right: this.formatStyle(box.right, "px"), height: this.formatStyle(box.height, "px"), width: this.formatStyle(box.width, "px") }); }; } CueStyleBox.prototype = _objCreate(StyleBox.prototype); CueStyleBox.prototype.constructor = CueStyleBox; // Represents the co-ordinates of an Element in a way that we can easily // compute things with such as if it overlaps or intersects with another Element. // Can initialize it with either a StyleBox or another BoxPosition. function BoxPosition(obj) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); // Either a BoxPosition was passed in and we need to copy it, or a StyleBox // was passed in and we need to copy the results of 'getBoundingClientRect' // as the object returned is readonly. All co-ordinate values are in reference // to the viewport origin (top left). var lh, height, width, top; if (obj.div) { height = obj.div.offsetHeight; width = obj.div.offsetWidth; top = obj.div.offsetTop; var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects(); obj = obj.div.getBoundingClientRect(); // In certain cases the outter div will be slightly larger then the sum of // the inner div's lines. This could be due to bold text, etc, on some platforms. // In this case we should get the average line height and use that. This will // result in the desired behaviour. lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length) : 0; } this.left = obj.left; this.right = obj.right; this.top = obj.top || top; this.height = obj.height || height; this.bottom = obj.bottom || (top + (obj.height || height)); this.width = obj.width || width; this.lineHeight = lh !== undefined ? lh : obj.lineHeight; if (isIE8 && !this.lineHeight) { this.lineHeight = 13; } } // Move the box along a particular axis. Optionally pass in an amount to move // the box. If no amount is passed then the default is the line height of the // box. BoxPosition.prototype.move = function(axis, toMove) { toMove = toMove !== undefined ? toMove : this.lineHeight; switch (axis) { case "+x": this.left += toMove; this.right += toMove; break; case "-x": this.left -= toMove; this.right -= toMove; break; case "+y": this.top += toMove; this.bottom += toMove; break; case "-y": this.top -= toMove; this.bottom -= toMove; break; } }; // Check if this box overlaps another box, b2. BoxPosition.prototype.overlaps = function(b2) { return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top; }; // Check if this box overlaps any other boxes in boxes. BoxPosition.prototype.overlapsAny = function(boxes) { for (var i = 0; i < boxes.length; i++) { if (this.overlaps(boxes[i])) { return true; } } return false; }; // Check if this box is within another box. BoxPosition.prototype.within = function(container) { return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right; }; // Check if this box is entirely within the container or it is overlapping // on the edge opposite of the axis direction passed. For example, if "+x" is // passed and the box is overlapping on the left edge of the container, then // return true. BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) { switch (axis) { case "+x": return this.left < container.left; case "-x": return this.right > container.right; case "+y": return this.top < container.top; case "-y": return this.bottom > container.bottom; } }; // Find the percentage of the area that this box is overlapping with another // box. BoxPosition.prototype.intersectPercentage = function(b2) { var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)), y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)), intersectArea = x * y; return intersectArea / (this.height * this.width); }; // Convert the positions from this box to CSS compatible positions using // the reference container's positions. This has to be done because this // box's positions are in reference to the viewport origin, whereas, CSS // values are in referecne to their respective edges. BoxPosition.prototype.toCSSCompatValues = function(reference) { return { top: this.top - reference.top, bottom: reference.bottom - this.bottom, left: this.left - reference.left, right: reference.right - this.right, height: this.height, width: this.width }; }; // Get an object that represents the box's position without anything extra. // Can pass a StyleBox, HTMLElement, or another BoxPositon. BoxPosition.getSimpleBoxPosition = function(obj) { var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0; var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0; var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0; obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj; var ret = { left: obj.left, right: obj.right, top: obj.top || top, height: obj.height || height, bottom: obj.bottom || (top + (obj.height || height)), width: obj.width || width }; return ret; }; // Move a StyleBox to its specified, or next best, position. The containerBox // is the box that contains the StyleBox, such as a div. boxPositions are // a list of other boxes that the styleBox can't overlap with. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) { // Find the best position for a cue box, b, on the video. The axis parameter // is a list of axis, the order of which, it will move the box along. For example: // Passing ["+x", "-x"] will move the box first along the x axis in the positive // direction. If it doesn't find a good position for it there it will then move // it along the x axis in the negative direction. function findBestPosition(b, axis) { var bestPosition, specifiedPosition = new BoxPosition(b), percentage = 1; // Highest possible so the first thing we get is better. for (var i = 0; i < axis.length; i++) { while (b.overlapsOppositeAxis(containerBox, axis[i]) || (b.within(containerBox) && b.overlapsAny(boxPositions))) { b.move(axis[i]); } // We found a spot where we aren't overlapping anything. This is our // best position. if (b.within(containerBox)) { return b; } var p = b.intersectPercentage(containerBox); // If we're outside the container box less then we were on our last try // then remember this position as the best position. if (percentage > p) { bestPosition = new BoxPosition(b); percentage = p; } // Reset the box position to the specified position. b = new BoxPosition(specifiedPosition); } return bestPosition || specifiedPosition; } var boxPosition = new BoxPosition(styleBox), cue = styleBox.cue, linePos = computeLinePos(cue), axis = []; // If we have a line number to align the cue to. if (cue.snapToLines) { var size; switch (cue.vertical) { case "": axis = [ "+y", "-y" ]; size = "height"; break; case "rl": axis = [ "+x", "-x" ]; size = "width"; break; case "lr": axis = [ "-x", "+x" ]; size = "width"; break; } var step = boxPosition.lineHeight, position = step * Math.round(linePos), maxPosition = containerBox[size] + step, initialAxis = axis[0]; // If the specified intial position is greater then the max position then // clamp the box to the amount of steps it would take for the box to // reach the max position. if (Math.abs(position) > maxPosition) { position = position < 0 ? -1 : 1; position *= Math.ceil(maxPosition / step) * step; } // If computed line position returns negative then line numbers are // relative to the bottom of the video instead of the top. Therefore, we // need to increase our initial position by the length or width of the // video, depending on the writing direction, and reverse our axis directions. if (linePos < 0) { position += cue.vertical === "" ? containerBox.height : containerBox.width; axis = axis.reverse(); } // Move the box to the specified position. This may not be its best // position. boxPosition.move(initialAxis, position); } else { // If we have a percentage line value for the cue. var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100; switch (cue.lineAlign) { case "middle": linePos -= (calculatedPercentage / 2); break; case "end": linePos -= calculatedPercentage; break; } // Apply initial line position to the cue box. switch (cue.vertical) { case "": styleBox.applyStyles({ top: styleBox.formatStyle(linePos, "%") }); break; case "rl": styleBox.applyStyles({ left: styleBox.formatStyle(linePos, "%") }); break; case "lr": styleBox.applyStyles({ right: styleBox.formatStyle(linePos, "%") }); break; } axis = [ "+y", "-x", "+x", "-y" ]; // Get the box position again after we've applied the specified positioning // to it. boxPosition = new BoxPosition(styleBox); } var bestPosition = findBestPosition(boxPosition, axis); styleBox.move(bestPosition.toCSSCompatValues(containerBox)); } function WebVTT() { // Nothing } // Helper to allow strings to be decoded instead of the default binary utf8 data. WebVTT.StringDecoder = function() { return { decode: function(data) { if (!data) { return ""; } if (typeof data !== "string") { throw new Error("Error - expected string data."); } return decodeURIComponent(encodeURIComponent(data)); } }; }; WebVTT.convertCueToDOMTree = function(window, cuetext) { if (!window || !cuetext) { return null; } return parseContent(window, cuetext); }; var FONT_SIZE_PERCENT = 0.05; var FONT_STYLE = "sans-serif"; var CUE_BACKGROUND_PADDING = "1.5%"; // Runs the processing model over the cues and regions passed to it. // @param overlay A block level element (usually a div) that the computed cues // and regions will be placed into. WebVTT.processCues = function(window, cues, overlay) { if (!window || !cues || !overlay) { return null; } // Remove all previous children. while (overlay.firstChild) { overlay.removeChild(overlay.firstChild); } var paddedOverlay = window.document.createElement("div"); paddedOverlay.style.position = "absolute"; paddedOverlay.style.left = "0"; paddedOverlay.style.right = "0"; paddedOverlay.style.top = "0"; paddedOverlay.style.bottom = "0"; paddedOverlay.style.margin = CUE_BACKGROUND_PADDING; overlay.appendChild(paddedOverlay); // Determine if we need to compute the display states of the cues. This could // be the case if a cue's state has been changed since the last computation or // if it has not been computed yet. function shouldCompute(cues) { for (var i = 0; i < cues.length; i++) { if (cues[i].hasBeenReset || !cues[i].displayState) { return true; } } return false; } // We don't need to recompute the cues' display states. Just reuse them. if (!shouldCompute(cues)) { for (var i = 0; i < cues.length; i++) { paddedOverlay.appendChild(cues[i].displayState); } return; } var boxPositions = [], containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay), fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100; var styleOptions = { font: fontSize + "px " + FONT_STYLE }; (function() { var styleBox, cue; for (var i = 0; i < cues.length; i++) { cue = cues[i]; // Compute the intial position and styles of the cue div. styleBox = new CueStyleBox(window, cue, styleOptions); paddedOverlay.appendChild(styleBox.div); // Move the cue div to it's correct line position. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions); // Remember the computed div so that we don't have to recompute it later // if we don't have too. cue.displayState = styleBox.div; boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox)); } })(); }; WebVTT.Parser = function(window, vttjs, decoder) { if (!decoder) { decoder = vttjs; vttjs = {}; } if (!vttjs) { vttjs = {}; } this.window = window; this.vttjs = vttjs; this.state = "INITIAL"; this.buffer = ""; this.decoder = decoder || new TextDecoder("utf8"); this.regionList = []; }; WebVTT.Parser.prototype = { // If the error is a ParsingError then report it to the consumer if // possible. If it's not a ParsingError then throw it like normal. reportOrThrowError: function(e) { if (e instanceof ParsingError) { this.onparsingerror && this.onparsingerror(e); } else { throw e; } }, parse: function (data) { var self = this; // If there is no data then we won't decode it, but will just try to parse // whatever is in buffer already. This may occur in circumstances, for // example when flush() is called. if (data) { // Try to decode the data that we received. self.buffer += self.decoder.decode(data, {stream: true}); } function collectNextLine() { var buffer = self.buffer; var pos = 0; while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') { ++pos; } var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below. if (buffer[pos] === '\r') { ++pos; } if (buffer[pos] === '\n') { ++pos; } self.buffer = buffer.substr(pos); return line; } // 3.4 WebVTT region and WebVTT region settings syntax function parseRegion(input) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "id": settings.set(k, v); break; case "width": settings.percent(k, v); break; case "lines": settings.integer(k, v); break; case "regionanchor": case "viewportanchor": var xy = v.split(','); if (xy.length !== 2) { break; } // We have to make sure both x and y parse, so use a temporary // settings object here. var anchor = new Settings(); anchor.percent("x", xy[0]); anchor.percent("y", xy[1]); if (!anchor.has("x") || !anchor.has("y")) { break; } settings.set(k + "X", anchor.get("x")); settings.set(k + "Y", anchor.get("y")); break; case "scroll": settings.alt(k, v, ["up"]); break; } }, /=/, /\s/); // Create the region, using default values for any values that were not // specified. if (settings.has("id")) { var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)(); region.width = settings.get("width", 100); region.lines = settings.get("lines", 3); region.regionAnchorX = settings.get("regionanchorX", 0); region.regionAnchorY = settings.get("regionanchorY", 100); region.viewportAnchorX = settings.get("viewportanchorX", 0); region.viewportAnchorY = settings.get("viewportanchorY", 100); region.scroll = settings.get("scroll", ""); // Register the region. self.onregion && self.onregion(region); // Remember the VTTRegion for later in case we parse any VTTCues that // reference it. self.regionList.push({ id: settings.get("id"), region: region }); } } // 3.2 WebVTT metadata header syntax function parseHeader(input) { parseOptions(input, function (k, v) { switch (k) { case "Region": // 3.3 WebVTT region metadata header syntax parseRegion(v); break; } }, /:/); } // 5.1 WebVTT file parsing. try { var line; if (self.state === "INITIAL") { // We can't start parsing until we have the first line. if (!/\r\n|\n/.test(self.buffer)) { return this; } line = collectNextLine(); var m = line.match(/^WEBVTT([ \t].*)?$/); if (!m || !m[0]) { throw new ParsingError(ParsingError.Errors.BadSignature); } self.state = "HEADER"; } var alreadyCollectedLine = false; while (self.buffer) { // We can't parse a line until we have the full line. if (!/\r\n|\n/.test(self.buffer)) { return this; } if (!alreadyCollectedLine) { line = collectNextLine(); } else { alreadyCollectedLine = false; } switch (self.state) { case "HEADER": // 13-18 - Allow a header (metadata) under the WEBVTT line. if (/:/.test(line)) { parseHeader(line); } else if (!line) { // An empty line terminates the header and starts the body (cues). self.state = "ID"; } continue; case "NOTE": // Ignore NOTE blocks. if (!line) { self.state = "ID"; } continue; case "ID": // Check for the start of NOTE blocks. if (/^NOTE($|[ \t])/.test(line)) { self.state = "NOTE"; break; } // 19-29 - Allow any number of line terminators, then initialize new cue values. if (!line) { continue; } self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, ""); self.state = "CUE"; // 30-39 - Check if self line contains an optional identifier or timing data. if (line.indexOf("-->") === -1) { self.cue.id = line; continue; } // Process line as start of a cue. /*falls through*/ case "CUE": // 40 - Collect cue timings and settings. try { parseCue(line, self.cue, self.regionList); } catch (e) { self.reportOrThrowError(e); // In case of an error ignore rest of the cue. self.cue = null; self.state = "BADCUE"; continue; } self.state = "CUETEXT"; continue; case "CUETEXT": var hasSubstring = line.indexOf("-->") !== -1; // 34 - If we have an empty line then report the cue. // 35 - If we have the special substring '-->' then report the cue, // but do not collect the line as we need to process the current // one as a new cue. if (!line || hasSubstring && (alreadyCollectedLine = true)) { // We are done parsing self cue. self.oncue && self.oncue(self.cue); self.cue = null; self.state = "ID"; continue; } if (self.cue.text) { self.cue.text += "\n"; } self.cue.text += line; continue; case "BADCUE": // BADCUE // 54-62 - Collect and discard the remaining cue. if (!line) { self.state = "ID"; } continue; } } } catch (e) { self.reportOrThrowError(e); // If we are currently parsing a cue, report what we have. if (self.state === "CUETEXT" && self.cue && self.oncue) { self.oncue(self.cue); } self.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise // another exception occurred so enter BADCUE state. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE"; } return this; }, flush: function () { var self = this; try { // Finish decoding the stream. self.buffer += self.decoder.decode(); // Synthesize the end of the current cue or region. if (self.cue || self.state === "HEADER") { self.buffer += "\n\n"; self.parse(); } // If we've flushed, parsed, and we're still on the INITIAL state then // that means we don't have enough of the stream to parse the first // line. if (self.state === "INITIAL") { throw new ParsingError(ParsingError.Errors.BadSignature); } } catch(e) { self.reportOrThrowError(e); } self.onflush && self.onflush(); return this; } }; global.WebVTT = WebVTT; }(this, (this.vttjs || {})));
docs/src/app/components/pages/components/CircularProgress/ExampleSimple.js
rhaedes/material-ui
import React from 'react'; import CircularProgress from 'material-ui/CircularProgress'; const CircularProgressExampleSimple = () => ( <div> <CircularProgress /> <CircularProgress size={1.5} /> <CircularProgress size={2} /> </div> ); export default CircularProgressExampleSimple;
src/app.js
ricca509/react-kit
import React from 'react'; import App from './components/App/App.react.js'; import Router from 'react-router'; import routes from './routes/routes.react.js'; Router.run(routes, function (Handler, state) { React.render(<Handler params={state.params} />, document.querySelector('[data-role="react-app"]')); });
資源/CCEI/DataTables-1.9.4/extras/AutoFill/media/docs/media/js/jquery.js
stevemoore113/ch_web_-
/*! * jQuery JavaScript Library v1.5.1 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Wed Feb 23 13:55:29 2011 -0500 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Check for digits rdigit = /\d/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // Has the ready events already been bound? readyBound = false, // The deferred used on DOM ready readyList, // Promise methods promiseMethods = "then done fail isResolved isRejected promise".split( " " ), // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = "body"; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? match = quickExpr.exec( selector ); // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return (context || rootjQuery).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.5.1", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + (this.selector ? " " : "") + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.done( fn ); return this; }, eq: function( i ) { return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { window.$ = _$; if ( deep ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Handle when the DOM is ready ready: function( wait ) { // A third-party is pushing the ready event forwards if ( wait === true ) { jQuery.readyWait--; } // Make sure that the DOM is not already loaded if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).unbind( "ready" ); } } }, bindReady: function() { if ( readyBound ) { return; } readyBound = true; // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent("onreadystatechange", DOMContentLoaded); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isNaN: function( obj ) { return obj == null || !rdigit.test( obj ) || isNaN( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test(data.replace(rvalidescape, "@") .replace(rvalidtokens, "]") .replace(rvalidbraces, "")) ) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); } }, // Cross-browser xml parsing // (xml & tmp used internally) parseXML: function( data , xml , tmp ) { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } tmp = xml.documentElement; if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evalulates a script in a global context globalEval: function( data ) { if ( data && rnotwhite.test(data) ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement, script = document.createElement( "script" ); if ( jQuery.support.scriptEval() ) { script.appendChild( document.createTextNode( data ) ); } else { script.text = data; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction(object); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type(array); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var ret = [], value; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, length = elems.length; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, proxy: function( fn, proxy, thisObject ) { if ( arguments.length === 2 ) { if ( typeof proxy === "string" ) { thisObject = fn; fn = thisObject[ proxy ]; proxy = undefined; } else if ( proxy && !jQuery.isFunction( proxy ) ) { thisObject = proxy; proxy = undefined; } } if ( !proxy && fn ) { proxy = function() { return fn.apply( thisObject || this, arguments ); }; } // Set the guid of unique handler to the same of original handler, so it can be removed if ( fn ) { proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; } // So proxy can be declared as an argument return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its a function access: function( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { jQuery.access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; }, now: function() { return (new Date()).getTime(); }, // Create a simple deferred (one callbacks list) _Deferred: function() { var // callbacks list callbacks = [], // stored [ context , args ] fired, // to avoid firing when already doing so firing, // flag to know if the deferred has been cancelled cancelled, // the deferred itself deferred = { // done( f1, f2, ...) done: function() { if ( !cancelled ) { var args = arguments, i, length, elem, type, _fired; if ( fired ) { _fired = fired; fired = 0; } for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { deferred.done.apply( deferred, elem ); } else if ( type === "function" ) { callbacks.push( elem ); } } if ( _fired ) { deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); } } return this; }, // resolve with given context and args resolveWith: function( context, args ) { if ( !cancelled && !fired && !firing ) { firing = 1; try { while( callbacks[ 0 ] ) { callbacks.shift().apply( context, args ); } } // We have to add a catch block for // IE prior to 8 or else the finally // block will never get executed catch (e) { throw e; } finally { fired = [ context, args ]; firing = 0; } } return this; }, // resolve with this as context and given arguments resolve: function() { deferred.resolveWith( jQuery.isFunction( this.promise ) ? this.promise() : this, arguments ); return this; }, // Has this deferred been resolved? isResolved: function() { return !!( firing || fired ); }, // Cancel cancel: function() { cancelled = 1; callbacks = []; return this; } }; return deferred; }, // Full fledged deferred (two callbacks list) Deferred: function( func ) { var deferred = jQuery._Deferred(), failDeferred = jQuery._Deferred(), promise; // Add errorDeferred methods, then and promise jQuery.extend( deferred, { then: function( doneCallbacks, failCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ); return this; }, fail: failDeferred.done, rejectWith: failDeferred.resolveWith, reject: failDeferred.resolve, isRejected: failDeferred.isResolved, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { if ( promise ) { return promise; } promise = obj = {}; } var i = promiseMethods.length; while( i-- ) { obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; } return obj; } } ); // Make sure only one callback list will be used deferred.done( failDeferred.cancel ).fail( deferred.cancel ); // Unexpose cancel delete deferred.cancel; // Call given func if any if ( func ) { func.call( deferred, deferred ); } return deferred; }, // Deferred helper when: function( object ) { var lastIndex = arguments.length, deferred = lastIndex <= 1 && object && jQuery.isFunction( object.promise ) ? object : jQuery.Deferred(), promise = deferred.promise(); if ( lastIndex > 1 ) { var array = slice.call( arguments, 0 ), count = lastIndex, iCallback = function( index ) { return function( value ) { array[ index ] = arguments.length > 1 ? slice.call( arguments, 0 ) : value; if ( !( --count ) ) { deferred.resolveWith( promise, array ); } }; }; while( ( lastIndex-- ) ) { object = array[ lastIndex ]; if ( object && jQuery.isFunction( object.promise ) ) { object.promise().then( iCallback(lastIndex), deferred.reject ); } else { --count; } } if ( !count ) { deferred.resolveWith( promise, array ); } } else if ( deferred !== object ) { deferred.resolve( object ); } return promise; }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySubclass( selector, context ) { return new jQuerySubclass.fn.init( selector, context ); } jQuery.extend( true, jQuerySubclass, this ); jQuerySubclass.superclass = this; jQuerySubclass.fn = jQuerySubclass.prototype = this(); jQuerySubclass.fn.constructor = jQuerySubclass; jQuerySubclass.subclass = this.subclass; jQuerySubclass.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySubclass) ) { context = jQuerySubclass(context); } return jQuery.fn.init.call( this, selector, context, rootjQuerySubclass ); }; jQuerySubclass.fn.init.prototype = jQuerySubclass.fn; var rootjQuerySubclass = jQuerySubclass(document); return jQuerySubclass; }, browser: {} }); // Create readyList deferred readyList = jQuery._Deferred(); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } if ( indexOf ) { jQuery.inArray = function( elem, array ) { return indexOf.call( array, elem ); }; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } // Expose jQuery to the global object return jQuery; })(); (function() { jQuery.support = {}; var div = document.createElement("div"); div.style.display = "none"; div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var all = div.getElementsByTagName("*"), a = div.getElementsByTagName("a")[0], select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ), input = div.getElementsByTagName("input")[0]; // Can't get basic test support if ( !all || !all.length || !a ) { return; } jQuery.support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText insted) style: /red/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55$/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: input.value === "on", // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Will be defined later deleteExpando: true, optDisabled: false, checkClone: false, noCloneEvent: true, noCloneChecked: true, boxModel: null, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableHiddenOffsets: true }; input.checked = true; jQuery.support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as diabled) select.disabled = true; jQuery.support.optDisabled = !opt.disabled; var _scriptEval = null; jQuery.support.scriptEval = function() { if ( _scriptEval === null ) { var root = document.documentElement, script = document.createElement("script"), id = "script" + jQuery.now(); try { script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); } catch(e) {} root.insertBefore( script, root.firstChild ); // Make sure that the execution of code works by injecting a script // tag with appendChild/createTextNode // (IE doesn't support this, fails, and uses .text instead) if ( window[ id ] ) { _scriptEval = true; delete window[ id ]; } else { _scriptEval = false; } root.removeChild( script ); // release memory in IE root = script = id = null; } return _scriptEval; }; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch(e) { jQuery.support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent("onclick", function click() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) jQuery.support.noCloneEvent = false; div.detachEvent("onclick", click); }); div.cloneNode(true).fireEvent("onclick"); } div = document.createElement("div"); div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; var fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // Figure out if the W3C box model works as expected // document.body must exist before we can do this jQuery(function() { var div = document.createElement("div"), body = document.getElementsByTagName("body")[0]; // Frameset documents with no body should not run this code if ( !body ) { return; } div.style.width = div.style.paddingLeft = "1px"; body.appendChild( div ); jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; if ( "zoom" in div.style ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.style.display = "inline"; div.style.zoom = 1; jQuery.support.inlineBlockNeedsLayout = div.offsetWidth === 2; // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = ""; div.innerHTML = "<div style='width:4px;'></div>"; jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2; } div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; var tds = div.getElementsByTagName("td"); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) jQuery.support.reliableHiddenOffsets = tds[0].offsetHeight === 0; tds[0].style.display = ""; tds[1].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE < 8 fail this test) jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0; div.innerHTML = ""; body.removeChild( div ).style.display = "none"; div = tds = null; }); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ var eventSupported = function( eventName ) { var el = document.createElement("div"); eventName = "on" + eventName; // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( !el.attachEvent ) { return true; } var isSupported = (eventName in el); if ( !isSupported ) { el.setAttribute(eventName, "return;"); isSupported = typeof el[eventName] === "function"; } el = null; return isSupported; }; jQuery.support.submitBubbles = eventSupported("submit"); jQuery.support.changeBubbles = eventSupported("change"); // release memory in IE div = all = a = null; })(); var rbrace = /^(?:\{.*\}|\[.*\])$/; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ jQuery.expando ] = id = ++jQuery.uuid; } else { id = jQuery.expando; } } if ( !cache[ id ] ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); } else { cache[ id ] = jQuery.extend(cache[ id ], name); } } thisCache = cache[ id ]; // Internal jQuery data is stored in a separate object inside the object's data // cache in order to avoid key collisions between internal data and user-defined // data if ( pvt ) { if ( !thisCache[ internalKey ] ) { thisCache[ internalKey ] = {}; } thisCache = thisCache[ internalKey ]; } if ( data !== undefined ) { thisCache[ name ] = data; } // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should // not attempt to inspect the internal events object using jQuery.data, as this // internal data object is undocumented and subject to change. if ( name === "events" && !thisCache[name] ) { return thisCache[ internalKey ] && thisCache[ internalKey ].events; } return getByName ? thisCache[ name ] : thisCache; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; if ( thisCache ) { delete thisCache[ name ]; // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !isEmptyDataObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( pvt ) { delete cache[ id ][ internalKey ]; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } var internalCache = cache[ id ][ internalKey ]; // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care if ( jQuery.support.deleteExpando || cache != window ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the entire user cache at once because it's faster than // iterating through each key, but we need to continue to persist internal // data if it existed if ( internalCache ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } cache[ id ][ internalKey ] = internalCache; // Otherwise, we need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist } else if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } else { elem[ jQuery.expando ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var data = null; if ( typeof key === "undefined" ) { if ( this.length ) { data = jQuery.data( this[0] ); if ( this[0].nodeType === 1 ) { var attr = this[0].attributes, name; for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = name.substr( 5 ); dataAttr( this[0], name, data[ name ] ); } } } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); // Try to fetch any internally stored data first if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); data = dataAttr( this[0], key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.each(function() { var $this = jQuery( this ), args = [ parts[0], value ]; $this.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); $this.triggerHandler( "changeData" + parts[1] + "!", args ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { data = elem.getAttribute( "data-" + key ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : !jQuery.isNaN( data ) ? parseFloat( data ) : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON // property to be considered empty objects; this property always exists in // order to make sure JSON.stringify does not expose internal metadata function isEmptyDataObject( obj ) { for ( var name in obj ) { if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { if ( !elem ) { return; } type = (type || "fx") + "queue"; var q = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( !data ) { return q || []; } if ( !q || jQuery.isArray(data) ) { q = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } return q; }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(); // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue", true ); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function( i ) { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue( type, function() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); } }); var rclass = /[\n\t\r]/g, rspaces = /\s+/, rreturn = /\r/g, rspecialurl = /^(?:href|src|style)$/, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rradiocheck = /^(?:radio|checkbox)$/i; jQuery.props = { "for": "htmlFor", "class": "className", readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", colspan: "colSpan", tabindex: "tabIndex", usemap: "useMap", frameborder: "frameBorder" }; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name, fn ) { return this.each(function(){ jQuery.attr( this, name, "" ); if ( this.nodeType === 1 ) { this.removeAttribute( name ); } }); }, addClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class")) ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspaces ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " ", setClass = elem.className; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { setClass += " " + classNames[c]; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split( rspaces ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[c] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspaces ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { if ( !arguments.length ) { var elem = this[0]; if ( elem ) { if ( jQuery.nodeName( elem, "option" ) ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } // We need to handle select boxes special if ( jQuery.nodeName( elem, "select" ) ) { var index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery(option).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; } // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { return elem.getAttribute("value") === null ? "on" : elem.value; } // Everything else, we just grab the value return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction(value); return this.each(function(i) { var self = jQuery(this), val = value; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call(this, i, self.val()); } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray(val) ) { val = jQuery.map(val, function (value) { return value == null ? "" : value + ""; }); } if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { this.checked = jQuery.inArray( self.val(), val ) >= 0; } else if ( jQuery.nodeName( this, "select" ) ) { var values = jQuery.makeArray(val); jQuery( "option", this ).each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { this.selectedIndex = -1; } } else { this.value = val; } }); } }); jQuery.extend({ attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { // don't get/set attributes on text, comment and attribute nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || elem.nodeType === 2 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery(elem)[name](value); } var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), // Whether we are setting (or getting) set = value !== undefined; // Try to normalize/fix the name name = notxml && jQuery.props[ name ] || name; // Only do all the following if this is a node (faster for style) if ( elem.nodeType === 1 ) { // These attributes require special treatment var special = rspecialurl.test( name ); // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( name === "selected" && !jQuery.support.optSelected ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } // If applicable, access the attribute via the DOM 0 way // 'in' checks fail in Blackberry 4.7 #6931 if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) { if ( set ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } if ( value === null ) { if ( elem.nodeType === 1 ) { elem.removeAttribute( name ); } } else { elem[ name ] = value; } } // browsers index elements by id/name on forms, give priority to attributes. if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { return elem.getAttributeNode( name ).nodeValue; } // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ if ( name === "tabIndex" ) { var attributeNode = elem.getAttributeNode( "tabIndex" ); return attributeNode && attributeNode.specified ? attributeNode.value : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } return elem[ name ]; } if ( !jQuery.support.style && notxml && name === "style" ) { if ( set ) { elem.style.cssText = "" + value; } return elem.style.cssText; } if ( set ) { // convert the value to a string (all browsers do this but IE) see #1070 elem.setAttribute( name, "" + value ); } // Ensure that missing attributes return undefined // Blackberry 4.7 returns "" from getAttribute #6938 if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) { return undefined; } var attr = !jQuery.support.hrefNormalized && notxml && special ? // Some attributes require a special call on IE elem.getAttribute( name, 2 ) : elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return attr === null ? undefined : attr; } // Handle everything which isn't a DOM element node if ( set ) { elem[ name ] = value; } return elem[ name ]; } }); var rnamespaces = /\.(.*)$/, rformElems = /^(?:textarea|input|select)$/i, rperiod = /\./g, rspace = / /g, rescape = /[^\w\s.|`]/g, fcleanup = function( nm ) { return nm.replace(rescape, "\\$&"); }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // TODO :: Use a try/catch until it's safe to pull this out (likely 1.6) // Minor release fix for bug #8018 try { // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) { elem = window; } } catch ( e ) {} if ( handler === false ) { handler = returnFalse; } else if ( !handler ) { // Fixes bug #7229. Fix recommended by jdalton return; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery._data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } var events = elemData.events, eventHandle = elemData.handle; if ( !events ) { elemData.events = events = {}; } if ( !eventHandle ) { elemData.handle = eventHandle = function() { // Handle the second event of a trigger and when // an event is called after a page has unloaded return typeof jQuery !== "undefined" && !jQuery.event.triggered ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; if ( !handleObj.guid ) { handleObj.guid = handler.guid; } // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // Only use addEventListener/attachEvent if the special // events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have been used, for global triggering jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ), events = elemData && elemData.events; if ( !elemData || !events ) { return; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem, undefined, true ); } } }, // bubbling is internal trigger: function( event, data, elem /*, bubbling */ ) { // Event object or event type var type = event.type || event, bubbling = arguments[3]; if ( !bubbling ) { event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal jQuery.extend( jQuery.Event(type), event ) : // Just the event type (string) jQuery.Event(type); if ( type.indexOf("!") >= 0 ) { event.type = type = type.slice(0, -1); event.exclusive = true; } // Handle a global trigger if ( !elem ) { // Don't bubble custom events when global (to avoid too much overhead) event.stopPropagation(); // Only trigger if we've ever bound an event for it if ( jQuery.event.global[ type ] ) { // XXX This code smells terrible. event.js should not be directly // inspecting the data cache jQuery.each( jQuery.cache, function() { // internalKey variable is just used to make it easier to find // and potentially change this stuff later; currently it just // points to jQuery.expando var internalKey = jQuery.expando, internalCache = this[ internalKey ]; if ( internalCache && internalCache.events && internalCache.events[ type ] ) { jQuery.event.trigger( event, data, internalCache.handle.elem ); } }); } } // Handle triggering a single element // don't do events on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // Clean up in case it is reused event.result = undefined; event.target = elem; // Clone the incoming data, if any data = jQuery.makeArray( data ); data.unshift( event ); } event.currentTarget = elem; // Trigger the event, it is assumed that "handle" is a function var handle = jQuery._data( elem, "handle" ); if ( handle ) { handle.apply( elem, data ); } var parent = elem.parentNode || elem.ownerDocument; // Trigger an inline bound script try { if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { event.result = false; event.preventDefault(); } } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (inlineError) {} if ( !event.isPropagationStopped() && parent ) { jQuery.event.trigger( event, data, parent, true ); } else if ( !event.isDefaultPrevented() ) { var old, target = event.target, targetType = type.replace( rnamespaces, "" ), isClick = jQuery.nodeName( target, "a" ) && targetType === "click", special = jQuery.event.special[ targetType ] || {}; if ( (!special._default || special._default.call( elem, event ) === false) && !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { try { if ( target[ targetType ] ) { // Make sure that we don't accidentally re-trigger the onFOO events old = target[ "on" + targetType ]; if ( old ) { target[ "on" + targetType ] = null; } jQuery.event.triggered = true; target[ targetType ](); } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (triggerError) {} if ( old ) { target[ "on" + targetType ] = old; } jQuery.event.triggered = false; } } }, handle: function( event ) { var all, handlers, namespaces, namespace_re, events, namespace_sort = [], args = jQuery.makeArray( arguments ); event = args[0] = jQuery.event.fix( event || window.event ); event.currentTarget = this; // Namespaced event handlers all = event.type.indexOf(".") < 0 && !event.exclusive; if ( !all ) { namespaces = event.type.split("."); event.type = namespaces.shift(); namespace_sort = namespaces.slice(0).sort(); namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.namespace = event.namespace || namespace_sort.join("."); events = jQuery._data(this, "events"); handlers = (events || {})[ event.type ]; if ( events && handlers ) { // Clone the handlers to prevent manipulation handlers = handlers.slice(0); for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Filter the functions by class if ( all || namespace_re.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } } return event.result; }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { // Fixes #1925 where srcElement might not be defined either event.target = event.srcElement || document; } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add which for key events if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { event.which = event.charCode != null ? event.charCode : event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, liveConvert( handleObj.origType, handleObj.selector ), jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); }, remove: function( handleObj ) { jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); } }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { // Chrome does something similar, the parentNode property // can be accessed but is null. if ( parent !== document && !parent.parentNode ) { return; } // Traverse up the tree while ( parent && parent !== this ) { parent = parent.parentNode; } if ( parent !== this ) { // set the correct event type event.type = event.data; // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } // assuming we've left the element since we most likely mousedover a xul element } catch(e) { } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( this.nodeName && this.nodeName.toLowerCase() !== "form" ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var changeFilters, getVal = function( elem ) { var type = elem.type, val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( elem.nodeName.toLowerCase() === "select" ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery._data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery._data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; e.liveFired = undefined; jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, beforedeactivate: testChange, click: function( e ) { var elem = e.target, type = elem.type; if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = elem.type; if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information beforeactivate: function( e ) { var elem = e.target; jQuery._data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return rformElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return rformElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; // Handle when the input is .focus()'d changeFilters.focus = changeFilters.beforeactivate; } function trigger( type, elem, args ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. // Don't pass args or remember liveFired; they apply to the donor event. var event = jQuery.extend( {}, args[ 0 ] ); event.type = type; event.originalEvent = {}; event.liveFired = undefined; jQuery.event.handle.call( elem, event ); if ( event.isDefaultPrevented() ) { args[ 0 ].preventDefault(); } } // Create "bubbling" focus and blur events if ( document.addEventListener ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { jQuery.event.special[ fix ] = { setup: function() { this.addEventListener( orig, handler, true ); }, teardown: function() { this.removeEventListener( orig, handler, true ); } }; function handler( e ) { e = jQuery.event.fix( e ); e.type = fix; return jQuery.event.handle.call( this, e ); } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( jQuery.isFunction( data ) || data === false ) { fn = data; data = undefined; } var handler = name === "one" ? jQuery.proxy( fn, function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }) : fn; if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { var event = jQuery.Event( type ); event.preventDefault(); event.stopPropagation(); jQuery.event.trigger( event, data, this[0] ); return event.result; } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, i = 1; // link all the functions, so any of them can unbind this click handler while ( i < args.length ) { jQuery.proxy( fn, args[ i++ ] ); } return this.click( jQuery.proxy( fn, function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; })); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( typeof types === "object" && !types.preventDefault ) { for ( var key in types ) { context[ name ]( key, data, types[key], selector ); } return this; } if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( type === "focus" || type === "blur" ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler for ( var j = 0, l = context.length; j < l; j++ ) { jQuery.event.add( context[j], "live." + liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); } } else { // unbind live handler context.unbind( "live." + liveConvert( type, selector ), fn ); } } return this; }; }); function liveHandler( event ) { var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, elems = [], selectors = [], events = jQuery._data( this, "events" ); // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { return; } if ( event.namespace ) { namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { close = match[i]; for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { elem = close.elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { event.type = handleObj.preType; related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj, level: close.level }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; if ( maxLevel && match.level > maxLevel ) { break; } event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; ret = match.handleObj.origHandler.apply( match.elem, arguments ); if ( ret === false || event.isPropagationStopped() ) { maxLevel = match.level; if ( ret === false ) { stop = false; } if ( event.isImmediatePropagationStopped() ) { break; } } } return stop; } function liveConvert( type, selector ) { return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&"); } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.bind( name, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var match, type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var found, item, filter = Expr.filter[ type ], left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return "text" === elem.getAttribute( 'type' ); }, radio: function( elem ) { return "radio" === elem.type; }, checkbox: function( elem ) { return "checkbox" === elem.type; }, file: function( elem ) { return "file" === elem.type; }, password: function( elem ) { return "password" === elem.type; }, submit: function( elem ) { return "submit" === elem.type; }, image: function( elem ) { return "image" === elem.type; }, reset: function( elem ) { return "reset" === elem.type; }, button: function( elem ) { return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // If the nodes are siblings (or identical) we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Utility function for retreiving the text value of an array of DOM nodes Sizzle.getText = function( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += Sizzle.getText( elem.childNodes ); } } return ret; }; // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector, pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } if ( matches ) { Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { return matches.call( node, expr ); } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.POS, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var ret = this.pushStack( "", "find", selector ), length = 0; for ( var i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( var n = length; n < ret.length; n++ ) { for ( var r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && jQuery.filter( selector, this ).length > 0; }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; if ( jQuery.isArray( selectors ) ) { var match, selector, matches = {}, level = 1; if ( cur && selectors.length ) { for ( i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[selector] ) { matches[selector] = jQuery.expr.match.POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[selector]; if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { ret.push({ selector: selector, elem: cur, level: level }); } } cur = cur.parentNode; level++; } } return ret; } var pos = POS.test( selectors ) ? jQuery( selectors, context || this.context ) : null; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context ) { break; } } } } ret = ret.length > 1 ? jQuery.unique(ret) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ), // The variable 'args' was introduced in // https://github.com/jquery/jquery/commit/52a0238 // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. // http://code.google.com/p/v8/issues/detail?id=1050 args = slice.call(arguments); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, args.join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return (elem === qualifier) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return (jQuery.inArray( elem, qualifier ) >= 0) === keep; }); } var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<(?:script|object|embed|option|style)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery( this ); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append(this); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { return this.each(function() { jQuery( this ).wrapAll( html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ); } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || (l > 1 && i < lastIndex) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var internalKey = jQuery.expando, oldData = jQuery.data( src ), curData = jQuery.data( dest, oldData ); // Switch to use the internal data object, if it exists, for the next // stage of data copying if ( (oldData = oldData[ internalKey ]) ) { var events = oldData.events; curData = curData[ internalKey ] = jQuery.extend({}, oldData); if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data ); } } } } } function cloneFixAttributes(src, dest) { // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } var nodeName = dest.nodeName.toLowerCase(); // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want dest.clearAttributes(); // mergeAttributes, in contrast, only merges back on the // original attributes, not the events dest.mergeAttributes(src); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults ) { if ( cacheresults !== 1 ) { fragment = cacheresults; } } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( "getElementsByTagName" in elem ) { return elem.getElementsByTagName( "*" ); } else if ( "querySelectorAll" in elem ) { return elem.querySelectorAll( "*" ); } else { return []; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var clone = elem.cloneNode(true), srcElements, destElements, i; if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName // instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = []; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" && !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else if ( typeof elem === "string" ) { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( var j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { for ( i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ] && cache[ id ][ internalKey ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rdashAlpha = /-([a-z])/ig, rupper = /([A-Z])/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle, fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity", "opacity" ); return ret === "" ? "1" : ret; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "zIndex": true, "fontWeight": true, "opacity": true, "zoom": true, "lineHeight": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { // Make sure that NaN and null values aren't set. See: #7116 if ( typeof value === "number" && isNaN( value ) || value == null ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( typeof value === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { // Make sure that we're working with the right name var ret, origName = jQuery.camelCase( name ), hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name, origName ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } }, camelCase: function( string ) { return string.replace( rdashAlpha, fcamelCase ); } }); // DEPRECATED, Use jQuery.css() instead jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { val = getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } if ( val <= 0 ) { val = curCSS( elem, name, name ); if ( val === "0px" && currentStyle ) { val = currentStyle( elem, name, name ); } if ( val != null ) { // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } } if ( val < 0 || val == null ) { val = elem.style[ name ]; // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } return typeof val === "string" ? val : val + "px"; } }, set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 value = parseFloat(value); if ( value >= 0 ) { return value + "px"; } } else { return value; } } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ? (parseFloat(RegExp.$1) / 100) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = jQuery.isNaN(value) ? "" : "alpha(opacity=" + value * 100 + ")", filter = style.filter || ""; style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : style.filter + ' ' + opacity; } }; } if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, newName, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( !(defaultView = elem.ownerDocument.defaultView) ) { return undefined; } if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, ret = elem.currentStyle && elem.currentStyle[ name ], rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ], style = elem.style; // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values left = style.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { var which = name === "width" ? cssWidth : cssHeight, val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return val; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.css( elem, "margin" + this )) || 0; } else { val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0; } }); return val; } if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /(?:^file|^widget|\-extension):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rucHeaders = /(^|\-)([a-z])/g, rucHeadersFunc = function( _, $1, $2 ) { return $1 + $2.toUpperCase(); }, rurl = /^([\w\+\.\-]+:)\/\/([^\/?#:]*)(?::(\d+))?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts; // #8138, IE may throw an exception when accessing // a field from document.location if document.domain has been set try { ajaxLocation = document.location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ); // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for(; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } //Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for(; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.bind( o, f ); }; } ); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; } ); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function ( target, settings ) { if ( !settings ) { // Only one parameter, we extend ajaxSettings settings = target; target = jQuery.extend( true, jQuery.ajaxSettings, settings ); } else { // target was provided, we extend into it jQuery.extend( true, target, jQuery.ajaxSettings, settings ); } // Flatten fields we don't want deep extended for( var field in { context: 1, url: 1 } ) { if ( field in settings ) { target[ field ] = settings[ field ]; } else if( field in jQuery.ajaxSettings ) { target[ field ] = jQuery.ajaxSettings[ field ]; } } return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, crossDomain: null, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": "*/*" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery._Deferred(), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { requestHeaders[ name.toLowerCase().replace( rucHeaders, rucHeadersFunc ) ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, statusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status ? 4 : 0; var isSuccess, success, error, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = statusText; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.done; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( !s.crossDomain ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefiler, stop there if ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { requestHeaders[ "Content-Type" ] = s.contentType; } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { requestHeaders[ "If-Modified-Since" ] = jQuery.lastModified[ ifModifiedKey ]; } if ( jQuery.etag[ ifModifiedKey ] ) { requestHeaders[ "If-None-Match" ] = jQuery.etag[ ifModifiedKey ]; } } // Set the Accepts header for the server, depending on the dataType requestHeaders.Accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) : s.accepts[ "*" ]; // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( status < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { jQuery.error( e ); } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); } ); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) && obj.length ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // If we see an array here, it is empty and should be treated as an empty // object if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) { add( prefix, "" ); // Serialize object item. } else { for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for( key in s.converters ) { if( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|()\?\?()/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var dataIsString = ( typeof s.data === "string" ); if ( s.dataTypes[ 0 ] === "jsonp" || originalSettings.jsonpCallback || originalSettings.jsonp != null || s.jsonp !== false && ( jsre.test( s.url ) || dataIsString && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2", cleanUp = function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( dataIsString ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Install cleanUp function jqXHR.then( cleanUp, cleanUp ); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } } ); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } } ); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } } ); var // #5280: next active xhr id and list of active xhrs' callbacks xhrId = jQuery.now(), xhrCallbacks, // XHR used to determine supports properties testXHR; // #5280: Internet Explorer will keep connections alive if we don't abort on unload function xhrOnUnloadAbort() { jQuery( window ).unload(function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } }); } // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Test if we can create an xhr object testXHR = jQuery.ajaxSettings.xhr(); jQuery.support.ajax = !!testXHR; // Does this browser support crossDomain XHR requests jQuery.support.cors = testXHR && ( "withCredentials" in testXHR ); // No need for the temporary xhr anymore testXHR = undefined; // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // Requested-With header // Not set for crossDomain requests with no content // (see why at http://trac.dojotoolkit.org/ticket/9486) // Won't change header if already provided if ( !( s.crossDomain && !s.hasContent ) && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; delete xhrCallbacks[ handle ]; } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } responses.text = xhr.responseText; // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; xhrOnUnloadAbort(); } // Add to list of active xhrs callbacks handle = xhrId++; xhr.onreadystatechange = xhrCallbacks[ handle ] = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var elemdisplay = {}, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ]; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[i]; display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( display === "" && jQuery.css( elem, "display" ) === "none" ) { jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName)); } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[i]; display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data(elem, "olddisplay") || ""; } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { var display = jQuery.css( this[i], "display" ); if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) { jQuery._data( this[i], "olddisplay", display ); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { this[i].style.display = "none"; } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete ); } return this[ optall.queue === false ? "each" : "queue" ](function() { // XXX 'this' does not always have a nodeName when running the // test suite var opt = jQuery.extend({}, optall), p, isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), self = this; for ( p in prop ) { var name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; p = name; } if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { return opt.complete.call(this); } if ( isElement && ( p === "height" || p === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height // animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { if ( !jQuery.support.inlineBlockNeedsLayout ) { this.style.display = "inline-block"; } else { var display = defaultDisplay(this.nodeName); // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( display === "inline" ) { this.style.display = "inline-block"; } else { this.style.display = "inline"; this.style.zoom = 1; } } } } if ( jQuery.isArray( prop[p] ) ) { // Create (if needed) and add to specialEasing (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; prop[p] = prop[p][0]; } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } opt.curAnim = jQuery.extend({}, prop); jQuery.each( prop, function( name, val ) { var e = new jQuery.fx( self, opt, name ); if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); } else { var parts = rfxnum.exec(val), start = e.cur(); if ( parts ) { var end = parseFloat( parts[2] ), unit = parts[3] || ( jQuery.cssNumber[ name ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( self, name, (end || 1) + unit); start = ((end || 1) / e.cur()) * start; jQuery.style( self, name, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ((parts[1] === "-=" ? -1 : 1) * end) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } }); // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { var timers = jQuery.timers; if ( clearQueue ) { this.queue([]); } this.each(function() { // go in reverse order so anything added to the queue during the loop is ignored for ( var i = timers.length - 1; i >= 0; i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction(easing) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function() { if ( opt.queue !== false ) { jQuery(this).dequeue(); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; if ( !options.orig ) { options.orig = {}; } } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); }, // Get the current size cur: function() { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = jQuery.now(); this.start = from; this.end = to; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); this.now = this.start; this.pos = this.state = 0; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval(fx.tick, fx.interval); } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { var t = jQuery.now(), done = true; if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; for ( var i in this.options.curAnim ) { if ( this.options.curAnim[i] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { var elem = this.elem, options = this.options; jQuery.each( [ "", "X", "Y" ], function (index, value) { elem.style[ "overflow" + value ] = options.overflow[index]; } ); } // Hide the element if the "hide" operation was done if ( this.options.hide ) { jQuery(this.elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( this.options.hide || this.options.show ) { for ( var p in this.options.curAnim ) { jQuery.style( this.elem, p, this.options.orig[p] ); } } // Execute the complete function this.options.complete.call( this.elem ); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; // Perform the easing function, defaults to swing var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timers = jQuery.timers; for ( var i = 0; i < timers.length; i++ ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var elem = jQuery("<" + nodeName + ">").appendTo("body"), display = elem.css("display"); elem.remove(); if ( display === "none" || display === "" ) { display = "block"; } elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0], box; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } try { box = elem.getBoundingClientRect(); } catch(e) {} var doc = elem.ownerDocument, docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = (win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ), scrollLeft = (win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft), top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0, html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed"; checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden"; innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); body = container = innerDiv = checkDiv = table = td = null; jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = (position === "absolute" && jQuery.inArray('auto', [curCSSTop, curCSSLeft]) > -1), props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is absolute if ( calculatePosition ) { curPosition = curElem.position(); } curTop = calculatePosition ? curPosition.top : parseInt( curCSSTop, 10 ) || 0; curLeft = calculatePosition ? curPosition.left : parseInt( curCSSLeft, 10 ) || 0; if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if (options.top != null) { props.top = (options.top - curOffset.top) + curTop; } if (options.left != null) { props.left = (options.left - curOffset.left) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function(val) { var elem = this[0], win; if ( !elem ) { return null; } if ( val !== undefined ) { // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery(win).scrollLeft(), i ? val : jQuery(win).scrollTop() ); } else { this[ method ] = val; } }); } else { win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function() { return this[0] ? parseFloat( jQuery.css( this[0], type, "padding" ) ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { return this[0] ? parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } if ( jQuery.isWindow( elem ) ) { // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat var docElemProp = elem.document.documentElement[ "client" + name ]; return elem.document.compatMode === "CSS1Compat" && docElemProp || elem.document.body[ "client" + name ] || docElemProp; // Get document width or height } else if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater return Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ); // Get or set width or height on the element } else if ( size === undefined ) { var orig = jQuery.css( elem, type ), ret = parseFloat( orig ); return jQuery.isNaN( ret ) ? orig : ret; // Set the width or height on the element (default to pixels if value is unitless) } else { return this.css( type, typeof size === "string" ? size : size + "px" ); } }; }); window.jQuery = window.$ = jQuery; })(window);
public/js/jquery-1.11.1.js
musethno/MGS
/*! * jQuery JavaScript Library v1.11.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-05-01T17:42Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var deletedIds = []; var slice = deletedIds.slice; var concat = deletedIds.concat; var push = deletedIds.push; var indexOf = deletedIds.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var version = "1.11.1", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1, IE<9 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: deletedIds.sort, splice: deletedIds.splice }; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( support.ownLast ) { for ( key in obj ) { return hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, type: function( obj ) { if ( obj == null ) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Support: Android<4.1, IE<9 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( indexOf ) { return indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; while ( j < len ) { first[ i++ ] = second[ j++ ]; } // Support: IE<9 // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) if ( len !== len ) { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: function() { return +( new Date() ); }, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v1.10.19 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-04-18 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select msallowclip=''><option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowclip^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); jQuery.fn.extend({ has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !(--remaining) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } }); /** * Clean-up method for dom ready events */ function detach() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } } /** * The ready event handler and self cleanup method */ function completed() { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; var strundefined = typeof undefined; // Support: IE<9 // Iteration over object's inherited properties before its own var i; for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Note: most support tests are defined in their respective modules. // false until the test is run support.inlineBlockNeedsLayout = false; // Execute ASAP in case we need to set body.style.zoom jQuery(function() { // Minified: var a,b,c,d var val, div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Return for frameset docs that don't have a body return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); if ( typeof div.style.zoom !== strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; if ( val ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); }); (function() { var div = document.createElement( "div" ); // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } // Null elements to avoid leaks in IE. div = null; })(); /** * Determines whether an object can have data */ jQuery.acceptData = function( elem ) { var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], nodeType = +elem.nodeType || 1; // Do not set data on non-element DOM nodes because it will not be cleared (#8335). return nodeType !== 1 && nodeType !== 9 ? false : // Nodes accept data unless otherwise specified; rejection can be conditional !noData || noData !== true && elem.getAttribute("classid") === noData; }; var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function internalData( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements (space-suffixed to avoid Object.prototype collisions) // throw uncatchable exceptions if you attempt to set expando properties noData: { "applet ": true, "embed ": true, // ...but Flash objects (which have this classid) *can* handle expandos "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[0], attrs = elem && elem.attributes; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { // Minified: var a,b,c var input = document.createElement( "input" ), div = document.createElement( "div" ), fragment = document.createDocumentFragment(); // Setup div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName( "tbody" ).length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) input.type = "checkbox"; input.checked = true; fragment.appendChild( input ); support.appendChecked = input.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE6-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // #11217 - WebKit loses check when the name is after the checked attribute fragment.appendChild( div ); div.innerHTML = "<input type='radio' checked='checked' name='t'/>"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() support.noCloneEvent = true; if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } })(); (function() { var i, eventName, div = document.createElement( "div" ); // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; if ( !(support[ i + "Bubbles" ] = eventName in window) ) { // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) div.setAttribute( eventName, "t" ); support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; } } // Null elements to avoid leaks in IE. div = null; })(); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: IE < 9, Android < 4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); jQuery._removeData( doc, fix ); } else { jQuery._data( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!support.noCloneEvent || !support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } (function() { var shrinkWrapBlocksVal; support.shrinkWrapBlocks = function() { if ( shrinkWrapBlocksVal != null ) { return shrinkWrapBlocksVal; } // Will be changed later if needed. shrinkWrapBlocksVal = false; // Minified: var b,c,d var div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); // Support: IE6 // Check if elements with layout shrink-wrap their children if ( typeof div.style.zoom !== strundefined ) { // Reset CSS: box-sizing; display; margin; border div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;" + "padding:1px;width:1px;zoom:1"; div.appendChild( document.createElement( "div" ) ).style.width = "5px"; shrinkWrapBlocksVal = div.offsetWidth !== 3; } body.removeChild( container ); return shrinkWrapBlocksVal; }; })(); var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles, curCSS, rposition = /^(top|right|bottom|left)$/; if ( window.getComputedStyle ) { getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; curCSS = function( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + ""; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, computed ) { var left, rs, rsLeft, ret, style = elem.style; computed = computed || getStyles( elem ); ret = computed ? computed[ name ] : undefined; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + "" || "auto"; }; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { var condition = conditionFn(); if ( condition == null ) { // The test was not ready at this point; screw the hook this time // but check again when needed next time. return; } if ( condition ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { // Minified: var b,c,d,e,f,g, h,i var div, style, a, pixelPositionVal, boxSizingReliableVal, reliableHiddenOffsetsVal, reliableMarginRightVal; // Setup div = document.createElement( "div" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName( "a" )[ 0 ]; style = a && a.style; // Finish early in limited (non-browser) environments if ( !style ) { return; } style.cssText = "float:left;opacity:.5"; // Support: IE<9 // Make sure that element opacity exists (as opposed to filter) support.opacity = style.opacity === "0.5"; // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!style.cssFloat; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" || style.WebkitBoxSizing === ""; jQuery.extend(support, { reliableHiddenOffsets: function() { if ( reliableHiddenOffsetsVal == null ) { computeStyleTests(); } return reliableHiddenOffsetsVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computeStyleTests(); } return boxSizingReliableVal; }, pixelPosition: function() { if ( pixelPositionVal == null ) { computeStyleTests(); } return pixelPositionVal; }, // Support: Android 2.3 reliableMarginRight: function() { if ( reliableMarginRightVal == null ) { computeStyleTests(); } return reliableMarginRightVal; } }); function computeStyleTests() { // Minified: var b,c,d,j var div, body, container, contents; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + "box-sizing:border-box;display:block;margin-top:1%;top:1%;" + "border:1px;padding:1px;width:4px;position:absolute"; // Support: IE<9 // Assume reasonable values in the absence of getComputedStyle pixelPositionVal = boxSizingReliableVal = false; reliableMarginRightVal = true; // Check for getComputedStyle so that this code is not run in IE<9. if ( window.getComputedStyle ) { pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; boxSizingReliableVal = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right contents = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding contents.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; contents.style.marginRight = contents.style.width = "0"; div.style.width = "1px"; reliableMarginRightVal = !parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight ); } // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; contents = div.getElementsByTagName( "td" ); contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; if ( reliableHiddenOffsetsVal ) { contents[ 0 ].style.display = ""; contents[ 1 ].style.display = "none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; } body.removeChild( container ); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== value ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Support: IE // Swallow errors from 'invalid' CSS values (#5509) try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !support.shrinkWrapBlocks() ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { style.display = display; } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { // Minified: var a,b,c,d,e var input, div, select, a, opt; // Setup div = document.createElement( "div" ); div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName("a")[ 0 ]; // First batch of tests. select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE8 only // Check if we can trust getAttribute("value") input = document.createElement( "input" ); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; })(); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) jQuery.trim( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) { // Support: IE6 // When new option element is added to select box we need to // force reflow of newly added node in order to workaround delay // of initialization properties try { option.selected = optionSet = true; } catch ( _ ) { // Will be executed only in IE6 option.scrollHeight; } } else { option.selected = false; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return options; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = support.getSetAttribute, getSetInput = support.input; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hook for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // Retrieve booleans specially jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; } : function( elem, name, isXML ) { if ( !isXML ) { return elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; } }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) if ( name === "value" || value === elem.getAttribute( name ) ) { return value; } } }; // Some attributes are constructed with empty-string values when not defined attrHandle.id = attrHandle.name = attrHandle.coords = function( elem, name, isXML ) { var ret; if ( !isXML ) { return (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; } }; // Fixing value retrieval on a button requires this module jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); if ( ret && ret.specified ) { return ret.value; } }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } if ( !support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } var rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } // Support: Safari, IE9+ // mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !support.enctype ) { jQuery.propFix.enctype = "encoding"; } var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g; jQuery.parseJSON = function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { // Support: Android 2.3 // Workaround failure to string-cast null input return window.JSON.parse( data + "" ); } var requireNonComma, depth = null, str = jQuery.trim( data + "" ); // Guard against invalid (and possibly dangerous) input by ensuring that nothing remains // after removing valid tokens return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) { // Force termination if we see a misplaced comma if ( requireNonComma && comma ) { depth = 0; } // Perform no more replacements after returning to outermost depth if ( depth === 0 ) { return token; } // Commas must not follow "[", "{", or "," requireNonComma = open || comma; // Determine new depth // array/object open ("[" or "{"): depth += true - false (increment) // array/object close ("]" or "}"): depth += false - true (decrement) // other cases ("," or primitive): depth += true - true (numeric cast) depth += !close - !open; // Remove this token return ""; }) ) ? ( Function( "return " + str ) )() : jQuery.error( "Invalid JSON: " + data ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType.charAt( 0 ) === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!support.reliableHiddenOffsets() && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ? // Support: IE6+ function() { // XHR cannot access local files, always use ActiveX for that case return !this.isLocal && // Support: IE7-8 // oldIE XHR does not support non-RFC2616 methods (#13240) // See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx // and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9 // Although this check for six methods instead of eight // since IE also does not support "trace" and "connect" /^(get|post|head|put|delete|options)$/i.test( this.type ) && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; var xhrId = 0, xhrCallbacks = {}, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE<10 // Open requests must be manually aborted on unload (#5280) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }); } // Determine support properties support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( options ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !options.crossDomain || support.cors ) { var callback; return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; // Open the socket xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { // Support: IE<9 // IE's ActiveXObject throws a 'Type Mismatch' exception when setting // request header to a null-value. // // To keep consistent with other XHR implementations, cast the value // to string and ignore `undefined`. if ( headers[ i ] !== undefined ) { xhr.setRequestHeader( i, headers[ i ] + "" ); } } // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( options.hasContent && options.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responses; // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Clean up delete xhrCallbacks[ id ]; callback = undefined; xhr.onreadystatechange = jQuery.noop; // Abort manually if needed if ( isAbort ) { if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; // Support: IE<10 // Accessing binary-data responseText throws an exception // (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && options.isLocal && !options.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, xhr.getAllResponseHeaders() ); } }; if ( !options.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { // Add to the list of active xhr callbacks xhr.onreadystatechange = xhrCallbacks[ id ] = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = jQuery.trim( url.slice( off, url.length ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
sites/all/modules/context/plugins/context_reaction_block.js
nolc/Drupal7
(function($){ Drupal.behaviors.contextReactionBlock = {attach: function(context) { $('form.context-editor:not(.context-block-processed)') .addClass('context-block-processed') .each(function() { var id = $(this).attr('id'); Drupal.contextBlockEditor = Drupal.contextBlockEditor || {}; $(this).bind('init.pageEditor', function(event) { Drupal.contextBlockEditor[id] = new DrupalContextBlockEditor($(this)); }); $(this).bind('start.pageEditor', function(event, context) { // Fallback to first context if param is empty. if (!context) { context = $(this).data('defaultContext'); } Drupal.contextBlockEditor[id].editStart($(this), context); }); $(this).bind('end.pageEditor', function(event) { Drupal.contextBlockEditor[id].editFinish(); }); }); // // Admin Form ======================================================= // // ContextBlockForm: Init. $('#context-blockform:not(.processed)').each(function() { $(this).addClass('processed'); Drupal.contextBlockForm = new DrupalContextBlockForm($(this)); Drupal.contextBlockForm.setState(); }); // ContextBlockForm: Attach block removal handlers. // Lives in behaviors as it may be required for attachment to new DOM elements. $('#context-blockform a.remove:not(.processed)').each(function() { $(this).addClass('processed'); $(this).click(function() { $(this).parents('tr').eq(0).remove(); Drupal.contextBlockForm.setState(); return false; }); }); }}; /** * Context block form. Default form for editing context block reactions. */ DrupalContextBlockForm = function(blockForm) { this.state = {}; this.setState = function() { $('table.context-blockform-region', blockForm).each(function() { var region = $(this).attr('id').split('context-blockform-region-')[1]; var blocks = []; $('tr', $(this)).each(function() { var bid = $(this).attr('id'); var weight = $(this).find('select').val(); blocks.push({'bid' : bid, 'weight' : weight}); }); Drupal.contextBlockForm.state[region] = blocks; }); // Serialize here and set form element value. $('form input.context-blockform-state').val(JSON.stringify(this.state)); // Hide enabled blocks from selector that are used $('table.context-blockform-region tr').each(function() { var bid = $(this).attr('id'); $('div.context-blockform-selector input[value='+bid+']').parents('div.form-item').eq(0).hide(); }); // Show blocks in selector that are unused $('div.context-blockform-selector input').each(function() { var bid = $(this).val(); if ($('table.context-blockform-region tr#'+bid).size() === 0) { $(this).parents('div.form-item').eq(0).show(); } }); }; // make sure we update the state right before submits, this takes care of an // apparent race condition between saving the state and the weights getting set // by tabledrag $('#ctools-export-ui-edit-item-form').submit(function() { Drupal.contextBlockForm.setState(); }); // Tabledrag // Add additional handlers to update our blocks. $.each(Drupal.settings.tableDrag, function(base) { var table = $('#' + base + ':not(.processed)', blockForm); if (table && table.is('.context-blockform-region')) { table.addClass('processed'); table.bind('mouseup', function(event) { Drupal.contextBlockForm.setState(); return; }); } }); // Add blocks to a region $('td.blocks a', blockForm).each(function() { $(this).click(function() { var region = $(this).attr('href').split('#')[1]; var selected = $("div.context-blockform-selector input:checked"); if (selected.size() > 0) { selected.each(function() { // create new block markup var block = document.createElement('tr'); var text = $(this).parents('div.form-item').eq(0).hide().children('label').text(); var select = '<div class="form-item form-type-select"><select class="tabledrag-hide form-select">'; var i; for (i = -10; i < 10; ++i) { select += '<option>' + i + '</option>'; } select += '</select></div>'; $(block).attr('id', $(this).attr('value')).addClass('draggable'); $(block).html("<td>"+ text + "</td><td>" + select + "</td><td><a href='' class='remove'>X</a></td>"); // add block item to region var base = "context-blockform-region-"+ region; Drupal.tableDrag[base].makeDraggable(block); $('table#'+base).append(block); if ($.cookie('Drupal.tableDrag.showWeight') == 1) { $('table#'+base).find('.tabledrag-hide').css('display', ''); $('table#'+base).find('.tabledrag-handle').css('display', 'none'); } else { $('table#'+base).find('.tabledrag-hide').css('display', 'none'); $('table#'+base).find('.tabledrag-handle').css('display', ''); } Drupal.attachBehaviors($('table#'+base)); Drupal.contextBlockForm.setState(); $(this).removeAttr('checked'); }); } return false; }); }); }; /** * Context block editor. AHAH editor for live block reaction editing. */ DrupalContextBlockEditor = function(editor) { this.editor = editor; this.state = {}; this.blocks = {}; this.regions = {}; // Category selector handler. // Also set to "Choose a category" option as browsers can retain // form values from previous page load. $('select.context-block-browser-categories', editor).change(function() { var category = $(this).val(); var params = { containment: 'document', revert: true, dropOnEmpty: true, placeholder: 'draggable-placeholder', forcePlaceholderSize: true, helper: 'clone', appendTo: 'body', connectWith: ($.ui.version === '1.6') ? ['.ui-sortable'] : '.ui-sortable' }; $('div.category', editor).hide().sortable('destroy'); $('div.category-'+category, editor).show().sortable(params); }); $('select.context-block-browser-categories', editor).val(0).change(); return this; }; DrupalContextBlockEditor.prototype.initBlocks = function(blocks) { var self = this; this.blocks = blocks; blocks.each(function() { if($(this).hasClass('context-block-empty')) { $(this).removeClass('context-block-hidden'); } $(this).addClass('draggable'); $(this).prepend($('<a class="context-block-handle"></a>')); $(this).prepend($('<a class="context-block-remove"></a>').click(function() { $(this).parent ('.block').eq(0).fadeOut('medium', function() { $(this).remove(); self.updateBlocks(); }); return false; })); }); }; DrupalContextBlockEditor.prototype.initRegions = function(regions) { this.regions = regions; }; /** * Update UI to match the current block states. */ DrupalContextBlockEditor.prototype.updateBlocks = function() { var browser = $('div.context-block-browser'); // For all enabled blocks, mark corresponding addables as having been added. $('.block, .admin-block').each(function() { var bid = $(this).attr('id').split('block-')[1]; // Ugh. $('#context-block-addable-'+bid, browser).draggable('disable').addClass('context-block-added').removeClass('context-block-addable'); }); // For all hidden addables with no corresponding blocks, mark as addable. $('.context-block-item', browser).each(function() { var bid = $(this).attr('id').split('context-block-addable-')[1]; if ($('#block-'+bid).size() === 0) { $(this).draggable('enable').removeClass('context-block-added').addClass('context-block-addable'); } }); // Mark empty regions. $(this.regions).each(function() { if ($('.block:has(a.context-block)', this).size() > 0) { $(this).removeClass('context-block-region-empty'); } else { $(this).addClass('context-block-region-empty'); } }); }; /** * Live update a region. */ DrupalContextBlockEditor.prototype.updateRegion = function(event, ui, region, op) { switch (op) { case 'over': $(region).removeClass('context-block-region-empty'); break; case 'out': if ( // jQuery UI 1.8 $('.draggable-placeholder', region).size() === 1 && $('.block:has(a.context-block)', region).size() == 0 // jQuery UI 1.6 // $('div.draggable-placeholder', region).size() === 0 && // $('div.block:has(a.context-block)', region).size() == 1 && // $('div.block:has(a.context-block)', region).attr('id') == ui.item.attr('id') ) { $(region).addClass('context-block-region-empty'); } break; } }; /** * Remove script elements while dragging & dropping. */ DrupalContextBlockEditor.prototype.scriptFix = function(event, ui, editor, context) { if ($('script', ui.item)) { var placeholder = $(Drupal.settings.contextBlockEditor.scriptPlaceholder); var label = $('div.handle label', ui.item).text(); placeholder.children('strong').html(label); $('script', ui.item).parent().empty().append(placeholder); } }; /** * Add a block to a region through an AHAH load of the block contents. */ DrupalContextBlockEditor.prototype.addBlock = function(event, ui, editor, context) { var self = this; if (ui.item.is('.context-block-addable')) { var bid = ui.item.attr('id').split('context-block-addable-')[1]; // Construct query params for our AJAX block request. var params = Drupal.settings.contextBlockEditor.params; params.context_block = bid + ',' + context; // Replace item with loading block. var blockLoading = $('<div class="context-block-item context-block-loading"><span class="icon"></span></div>'); ui.item.addClass('context-block-added'); ui.item.after(blockLoading); ui.sender.append(ui.item); $.getJSON(Drupal.settings.contextBlockEditor.path, params, function(data) { if (data.status) { var newBlock = $(data.block); if ($('script', newBlock)) { $('script', newBlock).remove(); } blockLoading.fadeOut(function() { $(this).replaceWith(newBlock); self.initBlocks(newBlock); self.updateBlocks(); Drupal.attachBehaviors(); }); } else { blockLoading.fadeOut(function() { $(this).remove(); }); } }); } else if (ui.item.is(':has(a.context-block)')) { self.updateBlocks(); } }; /** * Update form hidden field with JSON representation of current block visibility states. */ DrupalContextBlockEditor.prototype.setState = function() { var self = this; $(this.regions).each(function() { var region = $('a.context-block-region', this).attr('id').split('context-block-region-')[1]; var blocks = []; $('a.context-block', $(this)).each(function() { if ($(this).attr('class').indexOf('edit-') != -1) { var bid = $(this).attr('id').split('context-block-')[1]; var context = $(this).attr('class').split('edit-')[1].split(' ')[0]; context = context ? context : 0; var block = {'bid': bid, 'context': context}; blocks.push(block); } }); self.state[region] = blocks; }); // Serialize here and set form element value. $('input.context-block-editor-state', this.editor).val(JSON.stringify(this.state)); }; /** * Disable text selection. */ DrupalContextBlockEditor.prototype.disableTextSelect = function() { if ($.browser.safari) { $('.block:has(a.context-block):not(:has(input,textarea))').css('WebkitUserSelect','none'); } else if ($.browser.mozilla) { $('.block:has(a.context-block):not(:has(input,textarea))').css('MozUserSelect','none'); } else if ($.browser.msie) { $('.block:has(a.context-block):not(:has(input,textarea))').bind('selectstart.contextBlockEditor', function() { return false; }); } else { $(this).bind('mousedown.contextBlockEditor', function() { return false; }); } }; /** * Enable text selection. */ DrupalContextBlockEditor.prototype.enableTextSelect = function() { if ($.browser.safari) { $('*').css('WebkitUserSelect',''); } else if ($.browser.mozilla) { $('*').css('MozUserSelect',''); } else if ($.browser.msie) { $('*').unbind('selectstart.contextBlockEditor'); } else { $(this).unbind('mousedown.contextBlockEditor'); } }; /** * Start editing. Attach handlers, begin draggable/sortables. */ DrupalContextBlockEditor.prototype.editStart = function(editor, context) { var self = this; // This is redundant to the start handler found in context_ui.js. // However it's necessary that we trigger this class addition before // we call .sortable() as the empty regions need to be visible. $(document.body).addClass('context-editing'); this.editor.addClass('context-editing'); this.disableTextSelect(); this.initBlocks($('.block:has(a.context-block.edit-'+context+')')); this.initRegions($('a.context-block-region').parent()); this.updateBlocks(); // First pass, enable sortables on all regions. $(this.regions).each(function() { var region = $(this); var params = { containment: 'document', revert: true, dropOnEmpty: true, placeholder: 'draggable-placeholder', forcePlaceholderSize: true, items: '> .block:has(a.context-block.editable)', handle: 'a.context-block-handle', start: function(event, ui) { self.scriptFix(event, ui, editor, context); }, stop: function(event, ui) { self.addBlock(event, ui, editor, context); }, receive: function(event, ui) { self.addBlock(event, ui, editor, context); }, over: function(event, ui) { self.updateRegion(event, ui, region, 'over'); }, out: function(event, ui) { self.updateRegion(event, ui, region, 'out'); } }; region.sortable(params); }); // Second pass, hook up all regions via connectWith to each other. $(this.regions).each(function() { $(this).sortable('option', 'connectWith', ['.ui-sortable']); }); // Terrible, terrible workaround for parentoffset issue in Safari. // The proper fix for this issue has been committed to jQuery UI, but was // not included in the 1.6 release. Therefore, we do a browser agent hack // to ensure that Safari users are covered by the offset fix found here: // http://dev.jqueryui.com/changeset/2073. if ($.ui.version === '1.6' && $.browser.safari) { $.browser.mozilla = true; } }; /** * Finish editing. Remove handlers. */ DrupalContextBlockEditor.prototype.editFinish = function() { this.editor.removeClass('context-editing'); this.enableTextSelect(); // Remove UI elements. $(this.blocks).each(function() { $('a.context-block-handle, a.context-block-remove', this).remove(); if($(this).hasClass('context-block-empty')) { $(this).addClass('context-block-hidden'); } $(this).removeClass('draggable'); }); this.regions.sortable('destroy'); this.setState(); // Unhack the user agent. if ($.ui.version === '1.6' && $.browser.safari) { $.browser.mozilla = false; } }; })(jQuery);
Animate/react-motion-demo/src/components/Container.js
imuntil/React
import React from 'react' import ReactCSSTransitionGroup from 'react-addons-css-transition-group' // import style from './Container.css'; export default class Container extends React.Component { constructor(props, context) { super(props, context); } componentWillMount() { // document.body.style.margin = '0px' // // 这是防止页面被拖拽 // document.body.addEventListener('touchmove', (ev) => { // ev.preventDefault(); // }) } render() { return ( <ReactCSSTransitionGroup transitionName='transitionWrapper' component='div' // className={style.transitionWrapper} transitionEnterTimeout={5000} transitionLeaveTimeout={3000}> <div key={this.props.location.pathname} style={{position:'absolute', width: '100%'}}> { this.props.children } </div> </ReactCSSTransitionGroup> ) } }
app/containers/Contact/index.js
audoralc/pyxis
/* * * Contact * */ import React from 'react'; import Helmet from 'react-helmet'; import Header from 'components/Header'; import Footer from 'components/Footer'; import BodyContainer from 'components/BodyContainer'; import ContactForm from 'components/ContactForm'; import glamorous from 'glamorous'; const ContactInfo = glamorous.section({ background: '#28a28a', padding: '2em', fontSize: '1.25em', }) export default class Contact extends React.PureComponent { render() { const pageGrid = { display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr 1fr', gridTemplateRows: '1fr auto auto auto auto 10%', } const bodyReset = { display: 'flex', flexDirection: 'row', } const headerBlock ={ textAlign: 'center', } return ( <div style={pageGrid}> <Helmet title="Contact" meta={[ { name: 'description', content: 'Description of Contact' }]}/> <Header></Header> <BodyContainer> <div className="header_block" style={headerBlock}> <h1> Get in touch</h1> <h2>yes hello this will be clever whenever I get to writing copy</h2> </div> <div style={bodyReset}> <ContactForm> </ContactForm> <div> <ContactInfo> <address> 1530 Hesiod Way <br/> Elpis, GA 33333 <br /> <a href="mailto:help@pyxis.com"> help@pyxis.com </a> </address> </ContactInfo> <section > </section> </div> </div> </BodyContainer> <Footer></Footer> </div> ); } }
src/components/input.js
rxgx/react-timeframes
import React from 'react'; import Rx from 'rx'; export default class InputComponent extends React.Component { componentDidMount() { var element = this.refs.input.getDOMNode(); var inputs = Rx.DOM.keyup(element); inputs. pluck('target', 'value'). filter(text => !!text). filter(text => text.length). debounce(250). subscribe(this.submitValue); } submitValue(value) { console.log(`TODO: Need to send this text to state machine; ${value}`); } render() { var attrs = { className: 'field', name: this.props.name, //onBlur: this.onBlur, onChange: this.onInputChange, //onFocus: this.onFocus, //onKeyDown: this.onKeyDown, //onKeyUp: this.onKeyUp, ref: 'input', type: 'text' }; return React.DOM.input(attrs); } }
src/main.js
annxingyuan/chatscan
/** * App entry point */ // Polyfill import 'babel-polyfill'; // Libraries import React from 'react'; import ReactDOM from 'react-dom'; import { Router, browserHistory } from 'react-router'; // Routes import Routes from './common/components/Routes'; // Base styling import './common/base.css'; // ID of the DOM element to mount app on const DOM_APP_EL_ID = 'app'; // Render the router ReactDOM.render(( <Router history={browserHistory}> {Routes} </Router> ), document.getElementById(DOM_APP_EL_ID));
ajax/libs/ember-data.js/1.0.0-beta.8/ember-data.prod.js
Amomo/cdnjs
/*! * @overview Ember Data * @copyright Copyright 2011-2014 Tilde Inc. and contributors. * Portions Copyright 2011 LivingSocial Inc. * @license Licensed under MIT license (see license.js) * @version 1.0.0-beta.8.2a68c63a */ (function(global) { var define, requireModule, require, requirejs; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requirejs = require = requireModule = function(name) { requirejs._eak_seen = registry; if (seen[name]) { return seen[name]; } seen[name] = {}; if (!registry[name]) { throw new Error("Could not find module " + name); } var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(resolve(deps[i]))); } } var value = callback.apply(this, reified); return seen[name] = exports || value; function resolve(child) { if (child.charAt(0) !== '.') { return child; } var parts = child.split("/"); var parentBase = name.split("/").slice(0, -1); for (var i=0, l=parts.length; i<l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join("/"); } }; })(); define("activemodel-adapter/lib/main", ["./system","exports"], function(__dependency1__, __exports__) { "use strict"; var ActiveModelAdapter = __dependency1__.ActiveModelAdapter; var ActiveModelSerializer = __dependency1__.ActiveModelSerializer; var EmbeddedRecordsMixin = __dependency1__.EmbeddedRecordsMixin; __exports__.ActiveModelAdapter = ActiveModelAdapter; __exports__.ActiveModelSerializer = ActiveModelSerializer; __exports__.EmbeddedRecordsMixin = EmbeddedRecordsMixin; }); define("activemodel-adapter/lib/setup-container", ["../../ember-data/lib/system/container_proxy","./system/active_model_serializer","./system/active_model_adapter","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var ContainerProxy = __dependency1__["default"]; var ActiveModelSerializer = __dependency2__["default"]; var ActiveModelAdapter = __dependency3__["default"]; __exports__["default"] = function setupActiveModelAdapter(container, application){ var proxy = new ContainerProxy(container); proxy.registerDeprecations([ {deprecated: 'serializer:_ams', valid: 'serializer:-active-model'}, {deprecated: 'adapter:_ams', valid: 'adapter:-active-model'} ]); container.register('serializer:-active-model', ActiveModelSerializer); container.register('adapter:-active-model', ActiveModelAdapter); }; }); define("activemodel-adapter/lib/system", ["./system/embedded_records_mixin","./system/active_model_adapter","./system/active_model_serializer","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var EmbeddedRecordsMixin = __dependency1__["default"]; var ActiveModelAdapter = __dependency2__["default"]; var ActiveModelSerializer = __dependency3__["default"]; __exports__.EmbeddedRecordsMixin = EmbeddedRecordsMixin; __exports__.ActiveModelAdapter = ActiveModelAdapter; __exports__.ActiveModelSerializer = ActiveModelSerializer; }); define("activemodel-adapter/lib/system/active_model_adapter", ["../../../ember-data/lib/adapters","../../../ember-data/lib/system/adapter","../../../ember-inflector/lib/main","./active_model_serializer","./embedded_records_mixin","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { "use strict"; var RESTAdapter = __dependency1__.RESTAdapter; var InvalidError = __dependency2__.InvalidError; var pluralize = __dependency3__.pluralize; var ActiveModelSerializer = __dependency4__["default"]; var EmbeddedRecordsMixin = __dependency5__["default"]; /** @module ember-data */ var forEach = Ember.EnumerableUtils.forEach; var decamelize = Ember.String.decamelize, underscore = Ember.String.underscore; /** The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate with a JSON API that uses an underscored naming convention instead of camelCasing. It has been designed to work out of the box with the [active_model_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. This Adapter expects specific settings using ActiveModel::Serializers, `embed :ids, include: true` which sideloads the records. This adapter extends the DS.RESTAdapter by making consistent use of the camelization, decamelization and pluralization methods to normalize the serialized JSON into a format that is compatible with a conventional Rails backend and Ember Data. ## JSON Structure The ActiveModelAdapter expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` @class ActiveModelAdapter @constructor @namespace DS @extends DS.RESTAdapter **/ var ActiveModelAdapter = RESTAdapter.extend({ defaultSerializer: '-active-model', /** The ActiveModelAdapter overrides the `pathForType` method to build underscored URLs by decamelizing and pluralizing the object type name. ```js this.pathForType("famousPerson"); //=> "famous_people" ``` @method pathForType @param {String} type @return String */ pathForType: function(type) { var decamelized = decamelize(type); var underscored = underscore(decamelized); return pluralize(underscored); }, /** The ActiveModelAdapter overrides the `ajaxError` method to return a DS.InvalidError for all 422 Unprocessable Entity responses. A 422 HTTP response from the server generally implies that the request was well formed but the API was unable to process it because the content was not semantically correct or meaningful per the API. For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918 https://tools.ietf.org/html/rfc4918#section-11.2 @method ajaxError @param jqXHR @return error */ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var response = Ember.$.parseJSON(jqXHR.responseText), errors = {}; if (response.errors !== undefined) { var jsonErrors = response.errors; forEach(Ember.keys(jsonErrors), function(key) { errors[Ember.String.camelize(key)] = jsonErrors[key]; }); } return new InvalidError(errors); } else { return error; } } }); __exports__["default"] = ActiveModelAdapter; }); define("activemodel-adapter/lib/system/active_model_serializer", ["../../../ember-inflector/lib/main","../../../ember-data/lib/serializers/rest_serializer","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var singularize = __dependency1__.singularize; var RESTSerializer = __dependency2__["default"]; /** @module ember-data */ var get = Ember.get, forEach = Ember.EnumerableUtils.forEach, camelize = Ember.String.camelize, capitalize = Ember.String.capitalize, decamelize = Ember.String.decamelize, underscore = Ember.String.underscore; /** The ActiveModelSerializer is a subclass of the RESTSerializer designed to integrate with a JSON API that uses an underscored naming convention instead of camelCasing. It has been designed to work out of the box with the [active_model_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. This Serializer expects specific settings using ActiveModel::Serializers, `embed :ids, include: true` which sideloads the records. This serializer extends the DS.RESTSerializer by making consistent use of the camelization, decamelization and pluralization methods to normalize the serialized JSON into a format that is compatible with a conventional Rails backend and Ember Data. ## JSON Structure The ActiveModelSerializer expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` @class ActiveModelSerializer @namespace DS @extends DS.RESTSerializer */ var ActiveModelSerializer = RESTSerializer.extend({ // SERIALIZE /** Converts camelCased attributes to underscored when serializing. @method keyForAttribute @param {String} attribute @return String */ keyForAttribute: function(attr) { return decamelize(attr); }, /** Underscores relationship names and appends "_id" or "_ids" when serializing relationship keys. @method keyForRelationship @param {String} key @param {String} kind @return String */ keyForRelationship: function(key, kind) { key = decamelize(key); if (kind === "belongsTo") { return key + "_id"; } else if (kind === "hasMany") { return singularize(key) + "_ids"; } else { return key; } }, /* Does not serialize hasMany relationships by default. */ serializeHasMany: Ember.K, /** Underscores the JSON root keys when serializing. @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(data, type, record, options) { var root = underscore(decamelize(type.typeKey)); data[root] = this.serialize(record, options); }, /** Serializes a polymorphic type as a fully capitalized model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); if (belongsTo) { key = this.keyForAttribute(key); json[key + "_type"] = capitalize(belongsTo.constructor.typeKey); } }, // EXTRACT /** Add extra step to `DS.RESTSerializer.normalize` so links are normalized. If your payload looks like: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flagged_comments": "api/comments/flagged" } } } ``` The normalized version would look like this ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flaggedComments": "api/comments/flagged" } } } ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @return Object */ normalize: function(type, hash, prop) { this.normalizeLinks(hash); return this._super(type, hash, prop); }, /** Convert `snake_cased` links to `camelCase` @method normalizeLinks @param {Object} data */ normalizeLinks: function(data){ if (data.links) { var links = data.links; for (var link in links) { var camelizedLink = camelize(link); if (camelizedLink !== link) { links[camelizedLink] = links[link]; delete links[link]; } } } }, /** Normalize the polymorphic type from the JSON. Normalize: ```js { id: "1" minion: { type: "evil_minion", id: "12"} } ``` To: ```js { id: "1" minion: { type: "evilMinion", id: "12"} } ``` @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { var payloadKey, payload; if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { if (relationship.options.polymorphic) { payloadKey = this.keyForAttribute(key); payload = hash[payloadKey]; if (payload && payload.type) { payload.type = this.typeForRoot(payload.type); } else if (payload && relationship.kind === "hasMany") { var self = this; forEach(payload, function(single) { single.type = self.typeForRoot(single.type); }); } } else { payloadKey = this.keyForRelationship(key, relationship.kind); payload = hash[payloadKey]; } hash[key] = payload; if (key !== payloadKey) { delete hash[payloadKey]; } }, this); } } }); __exports__["default"] = ActiveModelSerializer; }); define("activemodel-adapter/lib/system/embedded_records_mixin", ["../../../ember-inflector/lib/main","exports"], function(__dependency1__, __exports__) { "use strict"; var get = Ember.get; var forEach = Ember.EnumerableUtils.forEach; var camelize = Ember.String.camelize; var pluralize = __dependency1__.pluralize; /** ## Using Embedded Records `DS.EmbeddedRecordsMixin` supports serializing embedded records. To set up embedded records, include the mixin when extending a serializer then define and configure embedded (model) relationships. Below is an example of a per-type serializer ('post' type). ```js App.PostSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: {embedded: 'always'}, comments: {serialize: 'ids'} } }) ``` The `attrs` option for a resource `{embedded: 'always'}` is shorthand for: ```js {serialize: 'records', deserialize: 'records'} ``` ### Configuring Attrs A resource's `attrs` option may be set to use `ids`, `records` or `no` for the `serialize` and `deserialize` settings. The `attrs` property can be set on the ApplicationSerializer or a per-type serializer. In the case where embedded JSON is expected while extracting a payoad (reading) the setting is `deserialize: 'records'`, there is no need to use `ids` when extracting as that is the default behavior without this mixin if you are using the vanilla ActiveModelAdapter. Likewise, to embed JSON in the payload while serializing `serialize: 'records'` is the setting to use. There is an option of not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you do not want the relationship sent at all, you can use `serialize: 'no'`. ### ActiveModelSerializer defaults If you do not overwrite `attrs` for a specific relationship, the `ActiveModelSerializer` will behave in the following way: BelongsTo: `{serialize:'id', deserialize:'id'}` HasMany: `{serialize:no, deserialize:'ids'}` ### Model Relationships Embedded records must have a model defined to be extracted and serialized. To successfully extract and serialize embedded records the model relationships must be setup correcty See the [defining relationships](/guides/models/defining-models/#toc_defining-relationships) section of the **Defining Models** guide page. Records without an `id` property are not considered embedded records, model instances must have an `id` property to be used with Ember Data. ### Example JSON payloads, Models and Serializers **When customizing a serializer it is imporant to grok what the cusomizations are, please read the docs for the methods this mixin provides, in case you need to modify to fit your specific needs.** For example review the docs for each method of this mixin: * [extractArray](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_extractArray) * [extractSingle](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_extractSingle) * [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo) * [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany) @class EmbeddedRecordsMixin @namespace DS */ var EmbeddedRecordsMixin = Ember.Mixin.create({ /** Serialize `belongsTo` relationship when it is configured as an embedded object. This example of an author model belongs to a post model: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), author: DS.belongsTo('author') }); Author = DS.Model.extend({ name: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded author ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: {embedded: 'always'} } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "author": { "id": "2" "name": "dhh" } } } ``` @method serializeBelongsTo @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeBelongsTo: function(record, json, relationship) { var attr = relationship.key; var attrs = this.get('attrs'); if (noSerializeOptionSpecified(attrs, attr)) { this._super(record, json, relationship); return; } var includeIds = hasSerializeIdsOption(attrs, attr); var includeRecords = hasSerializeRecordsOption(attrs, attr); var embeddedRecord = record.get(attr); if (includeIds) { key = this.keyForRelationship(attr, relationship.kind); if (!embeddedRecord) { json[key] = null; } else { json[key] = get(embeddedRecord, 'id'); } } else if (includeRecords) { var key = this.keyForRelationship(attr); if (!embeddedRecord) { json[key] = null; } else { json[key] = embeddedRecord.serialize({includeId: true}); this.removeEmbeddedForeignKey(record, embeddedRecord, relationship, json[key]); } } }, /** Serialize `hasMany` relationship when it is configured as embedded objects. This example of a post model has many comments: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), comments: DS.hasMany('comment') }); Comment = DS.Model.extend({ body: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded comments ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: {embedded: 'always'} } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` The attrs options object can use more specific instruction for extracting and serializing. When serializing, an option to embed `ids` or `records` can be set. When extracting the only option is `records`. So `{embedded: 'always'}` is shorthand for: `{serialize: 'records', deserialize: 'records'}` To embed the `ids` for a related object (using a hasMany relationship): ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: {serialize: 'ids', deserialize: 'records'} } }) ``` ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": ["1", "2"] } } ``` @method serializeHasMany @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeHasMany: function(record, json, relationship) { var attr = relationship.key; var attrs = this.get('attrs'); if (noSerializeOptionSpecified(attrs, attr)) { this._super(record, json, relationship); return; } var includeIds = hasSerializeIdsOption(attrs, attr); var includeRecords = hasSerializeRecordsOption(attrs, attr); var key; if (includeIds) { key = this.keyForRelationship(attr, relationship.kind); json[key] = get(record, attr).mapBy('id'); } else if (includeRecords) { key = this.keyForAttribute(attr); json[key] = get(record, attr).map(function(embeddedRecord) { var serializedEmbeddedRecord = embeddedRecord.serialize({includeId: true}); this.removeEmbeddedForeignKey(record, embeddedRecord, relationship, serializedEmbeddedRecord); return serializedEmbeddedRecord; }, this); } }, /** When serializing an embedded record, modify the property (in the json payload) that refers to the parent record (foreign key for relationship). Serializing a `belongsTo` relationship removes the property that refers to the parent record Serializing a `hasMany` relationship does not remove the property that refers to the parent record. @method removeEmbeddedForeignKey @param {DS.Model} record @param {DS.Model} embeddedRecord @param {Object} relationship @param {Object} json */ removeEmbeddedForeignKey: function (record, embeddedRecord, relationship, json) { if (relationship.kind === 'hasMany') { return; } else if (relationship.kind === 'belongsTo') { var parentRecord = record.constructor.inverseFor(relationship.key); if (parentRecord) { var name = parentRecord.name; var embeddedSerializer = this.store.serializerFor(embeddedRecord.constructor); var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind); if (parentKey) { delete json[parentKey]; } } } }, /** Extract an embedded object from the payload for a single object and add the object in the compound document (side-loaded) format instead. A payload with an attribute configured for embedded records needs to be extracted: ```js { "post": { "id": 1 "title": "Rails is omakase", "author": { "id": 2 "name": "dhh" } "comments": [] } } ``` Ember Data is expecting a payload with a compound document (side-loaded) like: ```js { "post": { "id": "1" "title": "Rails is omakase", "author": "2" "comments": [] }, "authors": [{ "id": "2" "post": "1" "name": "dhh" }] "comments": [] } ``` The payload's `author` attribute represents an object with a `belongsTo` relationship. The `post` attribute under `author` is the foreign key with the id for the post @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} primaryType @param {Object} payload @param {String} recordId @return Object the primary response to the original request */ extractSingle: function(store, primaryType, payload, recordId) { var root = this.keyForAttribute(primaryType.typeKey), partial = payload[root]; updatePayloadWithEmbedded(this, store, primaryType, payload, partial); return this._super(store, primaryType, payload, recordId); }, /** Extract embedded objects in an array when an attr is configured for embedded, and add them as side-loaded objects instead. A payload with an attr configured for embedded records needs to be extracted: ```js { "post": { "id": "1" "title": "Rails is omakase", "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` Ember Data is expecting a payload with compound document (side-loaded) like: ```js { "post": { "id": "1" "title": "Rails is omakase", "comments": ["1", "2"] }, "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } ``` The payload's `comments` attribute represents records in a `hasMany` relationship @method extractArray @param {DS.Store} store @param {subclass of DS.Model} primaryType @param {Object} payload @return {Array<Object>} The primary array that was returned in response to the original query. */ extractArray: function(store, primaryType, payload) { var root = this.keyForAttribute(primaryType.typeKey), partials = payload[pluralize(root)]; forEach(partials, function(partial) { updatePayloadWithEmbedded(this, store, primaryType, payload, partial); }, this); return this._super(store, primaryType, payload); } }); // checks config for attrs option to embedded (always) - serialize and deserialize function hasEmbeddedAlwaysOption(attrs, attr) { var option = attrsOption(attrs, attr); return option && option.embedded === 'always'; } // checks config for attrs option to serialize ids function hasSerializeRecordsOption(attrs, attr) { var alwaysEmbed = hasEmbeddedAlwaysOption(attrs, attr); var option = attrsOption(attrs, attr); return alwaysEmbed || (option && (option.serialize === 'records')); } // checks config for attrs option to serialize records function hasSerializeIdsOption(attrs, attr) { var option = attrsOption(attrs, attr); return option && (option.serialize === 'ids' || option.serialize === 'id'); } // checks config for attrs option to serialize records function noSerializeOptionSpecified(attrs, attr) { var option = attrsOption(attrs, attr); var serializeRecords = hasSerializeRecordsOption(attrs, attr); var serializeIds = hasSerializeIdsOption(attrs, attr); return !(option && (option.serialize || option.embedded)); } // checks config for attrs option to deserialize records // a defined option object for a resource is treated the same as // `deserialize: 'records'` function hasDeserializeRecordsOption(attrs, attr) { var alwaysEmbed = hasEmbeddedAlwaysOption(attrs, attr); var option = attrsOption(attrs, attr); var hasSerializingOption = option && (option.deserialize || option.serialize); return alwaysEmbed || hasSerializingOption /* option.deserialize === 'records' */; } function attrsOption(attrs, attr) { return attrs && (attrs[Ember.String.camelize(attr)] || attrs[attr]); } // chooses a relationship kind to branch which function is used to update payload // does not change payload if attr is not embedded function updatePayloadWithEmbedded(serializer, store, type, payload, partial) { var attrs = get(serializer, 'attrs'); if (!attrs) { return; } type.eachRelationship(function(key, relationship) { if (hasDeserializeRecordsOption(attrs, key)) { if (relationship.kind === "hasMany") { updatePayloadWithEmbeddedHasMany(serializer, store, key, relationship, payload, partial); } if (relationship.kind === "belongsTo") { updatePayloadWithEmbeddedBelongsTo(serializer, store, key, relationship, payload, partial); } } }); } // handles embedding for `hasMany` relationship function updatePayloadWithEmbeddedHasMany(serializer, store, primaryType, relationship, payload, partial) { var embeddedSerializer = store.serializerFor(relationship.type.typeKey); var primaryKey = get(serializer, 'primaryKey'); var attr = relationship.type.typeKey; // underscore forces the embedded records to be side loaded. // it is needed when main type === relationship.type var embeddedTypeKey = '_' + serializer.typeForRoot(relationship.type.typeKey); var expandedKey = serializer.keyForRelationship(primaryType, relationship.kind); var attribute = serializer.keyForAttribute(primaryType); var ids = []; if (!partial[attribute]) { return; } payload[embeddedTypeKey] = payload[embeddedTypeKey] || []; forEach(partial[attribute], function(data) { var embeddedType = store.modelFor(attr); updatePayloadWithEmbedded(embeddedSerializer, store, embeddedType, payload, data); ids.push(data[primaryKey]); payload[embeddedTypeKey].push(data); }); partial[expandedKey] = ids; delete partial[attribute]; } // handles embedding for `belongsTo` relationship function updatePayloadWithEmbeddedBelongsTo(serializer, store, primaryType, relationship, payload, partial) { var attrs = serializer.get('attrs'); if (!attrs || !(hasDeserializeRecordsOption(attrs, Ember.String.camelize(primaryType)) || hasDeserializeRecordsOption(attrs, primaryType))) { return; } var attr = relationship.type.typeKey; var _serializer = store.serializerFor(relationship.type.typeKey); var primaryKey = get(_serializer, 'primaryKey'); var embeddedTypeKey = Ember.String.pluralize(attr); // TODO don't use pluralize var expandedKey = _serializer.keyForRelationship(primaryType, relationship.kind); var attribute = _serializer.keyForAttribute(primaryType); if (!partial[attribute]) { return; } payload[embeddedTypeKey] = payload[embeddedTypeKey] || []; var embeddedType = store.modelFor(relationship.type.typeKey); // Recursive call for nested record updatePayloadWithEmbedded(_serializer, store, embeddedType, payload, partial[attribute]); partial[expandedKey] = partial[attribute].id; // Need to move an embedded `belongsTo` object into a pluralized collection payload[embeddedTypeKey].push(partial[attribute]); // Need a reference to the parent so relationship works between both `belongsTo` records partial[attribute][relationship.parentType.typeKey + '_id'] = partial.id; delete partial[attribute]; } __exports__["default"] = EmbeddedRecordsMixin; }); define("ember-data/lib/adapters", ["./adapters/fixture_adapter","./adapters/rest_adapter","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var FixtureAdapter = __dependency1__["default"]; var RESTAdapter = __dependency2__["default"]; __exports__.RESTAdapter = RESTAdapter; __exports__.FixtureAdapter = FixtureAdapter; }); define("ember-data/lib/adapters/fixture_adapter", ["../system/adapter","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var get = Ember.get, fmt = Ember.String.fmt, indexOf = Ember.EnumerableUtils.indexOf; var counter = 0; var Adapter = __dependency1__["default"]; /** `DS.FixtureAdapter` is an adapter that loads records from memory. It's primarily used for development and testing. You can also use `DS.FixtureAdapter` while working on the API but are not ready to integrate yet. It is a fully functioning adapter. All CRUD methods are implemented. You can also implement query logic that a remote system would do. It's possible to develop your entire application with `DS.FixtureAdapter`. For information on how to use the `FixtureAdapter` in your application please see the [FixtureAdapter guide](/guides/models/the-fixture-adapter/). @class FixtureAdapter @namespace DS @extends DS.Adapter */ var FixtureAdapter = Adapter.extend({ // by default, fixtures are already in normalized form serializer: null, /** If `simulateRemoteResponse` is `true` the `FixtureAdapter` will wait a number of milliseconds before resolving promises with the fixture values. The wait time can be configured via the `latency` property. @property simulateRemoteResponse @type {Boolean} @default true */ simulateRemoteResponse: true, /** By default the `FixtureAdapter` will simulate a wait of the `latency` milliseconds before resolving promises with the fixture values. This behavior can be turned off via the `simulateRemoteResponse` property. @property latency @type {Number} @default 50 */ latency: 50, /** Implement this method in order to provide data associated with a type @method fixturesForType @param {Subclass of DS.Model} type @return {Array} */ fixturesForType: function(type) { if (type.FIXTURES) { var fixtures = Ember.A(type.FIXTURES); return fixtures.map(function(fixture){ var fixtureIdType = typeof fixture.id; if(fixtureIdType !== "number" && fixtureIdType !== "string"){ throw new Error(fmt('the id property must be defined as a number or string for fixture %@', [fixture])); } fixture.id = fixture.id + ''; return fixture; }); } return null; }, /** Implement this method in order to query fixtures data @method queryFixtures @param {Array} fixture @param {Object} query @param {Subclass of DS.Model} type @return {Promise|Array} */ queryFixtures: function(fixtures, query, type) { }, /** @method updateFixtures @param {Subclass of DS.Model} type @param {Array} fixture */ updateFixtures: function(type, fixture) { if(!type.FIXTURES) { type.FIXTURES = []; } var fixtures = type.FIXTURES; this.deleteLoadedFixture(type, fixture); fixtures.push(fixture); }, /** Implement this method in order to provide json for CRUD methods @method mockJSON @param {Subclass of DS.Model} type @param {DS.Model} record */ mockJSON: function(store, type, record) { return store.serializerFor(type).serialize(record, { includeId: true }); }, /** @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record @return {String} id */ generateIdForRecord: function(store) { return "fixture-" + counter++; }, /** @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @return {Promise} promise */ find: function(store, type, id) { var fixtures = this.fixturesForType(type), fixture; if (fixtures) { fixture = Ember.A(fixtures).findProperty('id', id); } if (fixture) { return this.simulateRemoteCall(function() { return fixture; }, this); } }, /** @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @return {Promise} promise */ findMany: function(store, type, ids) { var fixtures = this.fixturesForType(type); if (fixtures) { fixtures = fixtures.filter(function(item) { return indexOf(ids, item.id) !== -1; }); } if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: function(store, type) { var fixtures = this.fixturesForType(type); return this.simulateRemoteCall(function() { return fixtures; }, this); }, /** @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: function(store, type, query, array) { var fixtures = this.fixturesForType(type); fixtures = this.queryFixtures(fixtures, query, type); if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ createRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ updateRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ deleteRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.deleteLoadedFixture(type, fixture); return this.simulateRemoteCall(function() { // no payload in a deletion return null; }); }, /* @method deleteLoadedFixture @private @param type @param record */ deleteLoadedFixture: function(type, record) { var existingFixture = this.findExistingFixture(type, record); if(existingFixture) { var index = indexOf(type.FIXTURES, existingFixture); type.FIXTURES.splice(index, 1); return true; } }, /* @method findExistingFixture @private @param type @param record */ findExistingFixture: function(type, record) { var fixtures = this.fixturesForType(type); var id = get(record, 'id'); return this.findFixtureById(fixtures, id); }, /* @method findFixtureById @private @param fixtures @param id */ findFixtureById: function(fixtures, id) { return Ember.A(fixtures).find(function(r) { if(''+get(r, 'id') === ''+id) { return true; } else { return false; } }); }, /* @method simulateRemoteCall @private @param callback @param context */ simulateRemoteCall: function(callback, context) { var adapter = this; return new Ember.RSVP.Promise(function(resolve) { if (get(adapter, 'simulateRemoteResponse')) { // Schedule with setTimeout Ember.run.later(function() { resolve(callback.call(context)); }, get(adapter, 'latency')); } else { // Asynchronous, but at the of the runloop with zero latency Ember.run.schedule('actions', null, function() { resolve(callback.call(context)); }); } }, "DS: FixtureAdapter#simulateRemoteCall"); } }); __exports__["default"] = FixtureAdapter; }); define("ember-data/lib/adapters/rest_adapter", ["../system/adapter","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var Adapter = __dependency1__["default"]; var get = Ember.get, set = Ember.set; var forEach = Ember.ArrayPolyfills.forEach; /** The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter. This adapter is designed around the idea that the JSON exchanged with the server should be conventional. ## JSON Structure The REST adapter expects the JSON returned from your server to follow these conventions. ### Object Root The JSON payload should be an object that contains the record inside a root property. For example, in response to a `GET` request for `/posts/1`, the JSON should look like this: ```js { "post": { "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" } } ``` ### Conventional Names Attribute names in your JSON payload should be the camelCased versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "person": { "firstName": "Barack", "lastName": "Obama", "occupation": "President" } } ``` ## Customization ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```js DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Person` would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```js DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` ### Headers customization Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. ```js App.ApplicationAdapter = DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` `headers` can also be used as a computed property to support dynamic headers. In the example below, the `session` object has been injected into an adapter by Ember's container. ```js App.ApplicationAdapter = DS.RESTAdapter.extend({ headers: function() { return { "API_KEY": this.get("session.authToken"), "ANOTHER_HEADER": "Some header value" }; }.property("session.authToken") }); ``` In some cases, your dynamic headers may require data from some object outside of Ember's observer system (for example `document.cookie`). You can use the [volatile](/api/classes/Ember.ComputedProperty.html#method_volatile) function to set the property into a non-chached mode causing the headers to be recomputed with every request. ```js App.ApplicationAdapter = DS.RESTAdapter.extend({ headers: function() { return { "API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"), "ANOTHER_HEADER": "Some header value" }; }.property().volatile(); }); ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter */ var RESTAdapter = Adapter.extend({ defaultSerializer: '-rest', /** Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```javascript DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Post` would now target `/api/1/post/`. @property namespace @type {String} */ /** An adapter can target other hosts by setting the `host` property. ```javascript DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` Requests for `App.Post` would now target `https://api.example.com/post/`. @property host @type {String} */ /** Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. For dynamic headers see [headers customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @property headers @type {Object} */ /** Called by the store in order to fetch the JSON for a given type and ID. The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. This method performs an HTTP `GET` request with the id provided as part of the query string. @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @return {Promise} promise */ find: function(store, type, id) { return this.ajax(this.buildURL(type.typeKey, id), 'GET'); }, /** Called by the store in order to fetch a JSON array for all of the records for a given type. The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: function(store, type, sinceToken) { var query; if (sinceToken) { query = { since: sinceToken }; } return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @return {Promise} promise */ findQuery: function(store, type, query) { return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as IDs. For example, if the original payload looks like: ```js { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2, 3 ] } ``` The IDs will be passed as a URL-encoded Array of IDs, in this form: ``` ids[]=1&ids[]=2&ids[]=3 ``` Many servers, such as Rails and PHP, will automatically convert this URL-encoded array into an Array for you on the server-side. If you want to encode the IDs, differently, just override this (one-line) method. The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @return {Promise} promise */ findMany: function(store, type, ids) { return this.ajax(this.buildURL(type.typeKey), 'GET', { data: { ids: ids } }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "comments": "/posts/1/comments" } } } ``` This method will be called with the parent record and `/posts/1/comments`. The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL. If the URL is host-relative (starting with a single slash), the request will use the host specified on the adapter (if any). @method findHasMany @param {DS.Store} store @param {DS.Model} record @param {String} url @return {Promise} promise */ findHasMany: function(store, record, url) { var host = get(this, 'host'), id = get(record, 'id'), type = record.constructor.typeKey; if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') { url = host + url; } return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a belongs-to relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "person": { "id": 1, "name": "Tom Dale", "links": { "group": "/people/1/group" } } } ``` This method will be called with the parent record and `/people/1/group`. The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL. @method findBelongsTo @param {DS.Store} store @param {DS.Model} record @param {String} url @return {Promise} promise */ findBelongsTo: function(store, record, url) { var id = get(record, 'id'), type = record.constructor.typeKey; return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store when a newly created record is saved via the `save` method on a model record instance. The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ createRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record, { includeId: true }); return this.ajax(this.buildURL(type.typeKey), "POST", { data: data }); }, /** Called by the store when an existing record is saved via the `save` method on a model record instance. The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ updateRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record); var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id), "PUT", { data: data }); }, /** Called by the store when a record is deleted. The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`. @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ deleteRecord: function(store, type, record) { var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id), "DELETE"); }, /** Builds a URL for a given type and optional ID. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). To override the pluralization see [pathForType](#method_pathForType). If an ID is specified, it adds the ID to the path generated for the type, separated by a `/`. @method buildURL @param {String} type @param {String} id @return {String} url */ buildURL: function(type, id) { var url = [], host = get(this, 'host'), prefix = this.urlPrefix(); if (type) { url.push(this.pathForType(type)); } if (id) { url.push(id); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url) { url = '/' + url; } return url; }, /** @method urlPrefix @private @param {String} path @param {String} parentUrl @return {String} urlPrefix */ urlPrefix: function(path, parentURL) { var host = get(this, 'host'), namespace = get(this, 'namespace'), url = []; if (path) { // Absolute path if (path.charAt(0) === '/') { if (host) { path = path.slice(1); url.push(host); } // Relative path } else if (!/^http(s)?:\/\//.test(path)) { url.push(parentURL); } } else { if (host) { url.push(host); } if (namespace) { url.push(namespace); } } if (path) { url.push(path); } return url.join('/'); }, /** Determines the pathname for a given type. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). ### Pathname customization For example if you have an object LineItem with an endpoint of "/line_items/". ```js App.ApplicationAdapter = DS.RESTAdapter.extend({ pathForType: function(type) { var decamelized = Ember.String.decamelize(type); return Ember.String.pluralize(decamelized); } }); ``` @method pathForType @param {String} type @return {String} path **/ pathForType: function(type) { var camelized = Ember.String.camelize(type); return Ember.String.pluralize(camelized); }, /** Takes an ajax response, and returns a relevant error. Returning a `DS.InvalidError` from this method will cause the record to transition into the `invalid` state and make the `errors` object available on the record. ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"]; return new DS.InvalidError(jsonErrors); } else { return error; } } }); ``` Note: As a correctness optimization, the default implementation of the `ajaxError` method strips out the `then` method from jquery's ajax response (jqXHR). This is important because the jqXHR's `then` method fulfills the promise with itself resulting in a circular "thenable" chain which may cause problems for some promise libraries. @method ajaxError @param {Object} jqXHR @return {Object} jqXHR */ ajaxError: function(jqXHR) { if (jqXHR && typeof jqXHR === 'object') { jqXHR.then = null; } return jqXHR; }, /** Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. When the server responds with a payload, Ember Data will call into `extractSingle` or `extractArray` (depending on whether the original query was for one record or many records). By default, `ajax` method has the following behavior: * It sets the response `dataType` to `"json"` * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be `application/json; charset=utf-8` * If the HTTP method is not `"GET"`, it stringifies the data passed in. The data is the serialized record in the case of a save. * Registers success and failure handlers. @method ajax @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} hash @return {Promise} promise */ ajax: function(url, type, hash) { var adapter = this; return new Ember.RSVP.Promise(function(resolve, reject) { hash = adapter.ajaxOptions(url, type, hash); hash.success = function(json) { Ember.run(null, resolve, json); }; hash.error = function(jqXHR, textStatus, errorThrown) { Ember.run(null, reject, adapter.ajaxError(jqXHR)); }; Ember.$.ajax(hash); }, "DS: RestAdapter#ajax " + type + " to " + url); }, /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} hash @return {Object} hash */ ajaxOptions: function(url, type, hash) { hash = hash || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = this; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } var headers = get(this, 'headers'); if (headers !== undefined) { hash.beforeSend = function (xhr) { forEach.call(Ember.keys(headers), function(key) { xhr.setRequestHeader(key, headers[key]); }); }; } return hash; } }); __exports__["default"] = RESTAdapter; }); define("ember-data/lib/core", ["exports"], function(__exports__) { "use strict"; /** @module ember-data */ /** All Ember Data methods and functions are defined inside of this namespace. @class DS @static */ var DS; if ('undefined' === typeof DS) { /** @property VERSION @type String @default '1.0.0-beta.8.2a68c63a' @static */ DS = Ember.Namespace.create({ VERSION: '1.0.0-beta.8.2a68c63a' }); if (Ember.libraries) { Ember.libraries.registerCoreLibrary('Ember Data', DS.VERSION); } } __exports__["default"] = DS; }); define("ember-data/lib/ember-initializer", ["./setup-container"], function(__dependency1__) { "use strict"; var setupContainer = __dependency1__["default"]; var K = Ember.K; /** @module ember-data */ /** This code initializes Ember-Data onto an Ember application. If an Ember.js developer defines a subclass of DS.Store on their application, as `App.ApplicationStore` (or via a module system that resolves to `store:application`) this code will automatically instantiate it and make it available on the router. Additionally, after an application's controllers have been injected, they will each have the store made available to them. For example, imagine an Ember.js application with the following classes: App.ApplicationStore = DS.Store.extend({ adapter: 'custom' }); App.PostsController = Ember.ArrayController.extend({ // ... }); When the application is initialized, `App.ApplicationStore` will automatically be instantiated, and the instance of `App.PostsController` will have its `store` property set to that instance. Note that this code will only be run if the `ember-application` package is loaded. If Ember Data is being used in an environment other than a typical application (e.g., node.js where only `ember-runtime` is available), this code will be ignored. */ Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "ember-data", initialize: setupContainer }); // Deprecated initializers to satisfy old code that depended on them Application.initializer({ name: "store", after: "ember-data", initialize: K }); Application.initializer({ name: "activeModelAdapter", before: "store", initialize: K }); Application.initializer({ name: "transforms", before: "store", initialize: K }); Application.initializer({ name: "data-adapter", before: "store", initialize: K }); Application.initializer({ name: "injectStore", before: "store", initialize: K }); }); }); define("ember-data/lib/ext/date", [], function() { "use strict"; /** @module ember-data */ /** Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601> © 2011 Colin Snover <http://zetafleet.com> Released under MIT license. @class Date @namespace Ember @static */ Ember.Date = Ember.Date || {}; var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ]; /** @method parse @param date */ Ember.Date.parse = function (date) { var timestamp, struct, minutesOffset = 0; // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string // before falling back to any implementation-specific date parsing, so that’s what we do, even if native // implementations could be faster // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; (k = numericKeys[i]); ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); } else { timestamp = origParse ? origParse(date) : NaN; } return timestamp; }; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) { Date.parse = Ember.Date.parse; } }); define("ember-data/lib/initializers/data_adapter", ["../system/debug/debug_adapter","exports"], function(__dependency1__, __exports__) { "use strict"; var DebugAdapter = __dependency1__["default"]; /** Configures a container with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeStoreInjections @param {Ember.Container} container */ __exports__["default"] = function initializeDebugAdapter(container){ container.register('data-adapter:main', DebugAdapter); }; }); define("ember-data/lib/initializers/store", ["../serializers","../adapters","../system/container_proxy","../system/store","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; var JSONSerializer = __dependency1__.JSONSerializer; var RESTSerializer = __dependency1__.RESTSerializer; var RESTAdapter = __dependency2__.RESTAdapter; var ContainerProxy = __dependency3__["default"]; var Store = __dependency4__["default"]; /** Configures a container for use with an Ember-Data store. Accepts an optional namespace argument. @method initializeStore @param {Ember.Container} container @param {Object} [application] an application namespace */ __exports__["default"] = function initializeStore(container, application){ container.register('store:main', container.lookupFactory('store:application') || (application && application.Store) || Store); // allow older names to be looked up var proxy = new ContainerProxy(container); proxy.registerDeprecations([ {deprecated: 'serializer:_default', valid: 'serializer:-default'}, {deprecated: 'serializer:_rest', valid: 'serializer:-rest'}, {deprecated: 'adapter:_rest', valid: 'adapter:-rest'} ]); // new go forward paths container.register('serializer:-default', JSONSerializer); container.register('serializer:-rest', RESTSerializer); container.register('adapter:-rest', RESTAdapter); // Eagerly generate the store so defaultStore is populated. // TODO: Do this in a finisher hook container.lookup('store:main'); }; }); define("ember-data/lib/initializers/store_injections", ["exports"], function(__exports__) { "use strict"; /** Configures a container with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeStoreInjections @param {Ember.Container} container */ __exports__["default"] = function initializeStoreInjections(container){ container.injection('controller', 'store', 'store:main'); container.injection('route', 'store', 'store:main'); container.injection('serializer', 'store', 'store:main'); container.injection('data-adapter', 'store', 'store:main'); }; }); define("ember-data/lib/initializers/transforms", ["../transforms","exports"], function(__dependency1__, __exports__) { "use strict"; var BooleanTransform = __dependency1__.BooleanTransform; var DateTransform = __dependency1__.DateTransform; var StringTransform = __dependency1__.StringTransform; var NumberTransform = __dependency1__.NumberTransform; /** Configures a container for use with Ember-Data transforms. @method initializeTransforms @param {Ember.Container} container */ __exports__["default"] = function initializeTransforms(container){ container.register('transform:boolean', BooleanTransform); container.register('transform:date', DateTransform); container.register('transform:number', NumberTransform); container.register('transform:string', StringTransform); }; }); define("ember-data/lib/main", ["./core","./ext/date","./system/store","./system/model","./system/changes","./system/adapter","./system/debug","./system/record_arrays","./system/record_array_manager","./adapters","./serializers/json_serializer","./serializers/rest_serializer","../../ember-inflector/lib/main","../../activemodel-adapter/lib/main","./transforms","./system/relationships","./ember-initializer","./setup-container","./system/container_proxy","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __dependency11__, __dependency12__, __dependency13__, __dependency14__, __dependency15__, __dependency16__, __dependency17__, __dependency18__, __dependency19__, __exports__) { "use strict"; /** Ember Data @module ember-data @main ember-data */ // support RSVP 2.x via resolve, but prefer RSVP 3.x's Promise.cast Ember.RSVP.Promise.cast = Ember.RSVP.Promise.cast || Ember.RSVP.resolve; var DS = __dependency1__["default"]; var Store = __dependency3__.Store; var PromiseArray = __dependency3__.PromiseArray; var PromiseObject = __dependency3__.PromiseObject; var Model = __dependency4__.Model; var Errors = __dependency4__.Errors; var RootState = __dependency4__.RootState; var attr = __dependency4__.attr; var AttributeChange = __dependency5__.AttributeChange; var RelationshipChange = __dependency5__.RelationshipChange; var RelationshipChangeAdd = __dependency5__.RelationshipChangeAdd; var RelationshipChangeRemove = __dependency5__.RelationshipChangeRemove; var OneToManyChange = __dependency5__.OneToManyChange; var ManyToNoneChange = __dependency5__.ManyToNoneChange; var OneToOneChange = __dependency5__.OneToOneChange; var ManyToManyChange = __dependency5__.ManyToManyChange; var InvalidError = __dependency6__.InvalidError; var Adapter = __dependency6__.Adapter; var DebugAdapter = __dependency7__["default"]; var RecordArray = __dependency8__.RecordArray; var FilteredRecordArray = __dependency8__.FilteredRecordArray; var AdapterPopulatedRecordArray = __dependency8__.AdapterPopulatedRecordArray; var ManyArray = __dependency8__.ManyArray; var RecordArrayManager = __dependency9__["default"]; var RESTAdapter = __dependency10__.RESTAdapter; var FixtureAdapter = __dependency10__.FixtureAdapter; var JSONSerializer = __dependency11__["default"]; var RESTSerializer = __dependency12__["default"]; var ActiveModelAdapter = __dependency14__.ActiveModelAdapter; var ActiveModelSerializer = __dependency14__.ActiveModelSerializer; var EmbeddedRecordsMixin = __dependency14__.EmbeddedRecordsMixin; var Transform = __dependency15__.Transform; var DateTransform = __dependency15__.DateTransform; var NumberTransform = __dependency15__.NumberTransform; var StringTransform = __dependency15__.StringTransform; var BooleanTransform = __dependency15__.BooleanTransform; var hasMany = __dependency16__.hasMany; var belongsTo = __dependency16__.belongsTo; var setupContainer = __dependency18__["default"]; var ContainerProxy = __dependency19__["default"]; DS.Store = Store; DS.PromiseArray = PromiseArray; DS.PromiseObject = PromiseObject; DS.Model = Model; DS.RootState = RootState; DS.attr = attr; DS.Errors = Errors; DS.AttributeChange = AttributeChange; DS.RelationshipChange = RelationshipChange; DS.RelationshipChangeAdd = RelationshipChangeAdd; DS.OneToManyChange = OneToManyChange; DS.ManyToNoneChange = OneToManyChange; DS.OneToOneChange = OneToOneChange; DS.ManyToManyChange = ManyToManyChange; DS.Adapter = Adapter; DS.InvalidError = InvalidError; DS.DebugAdapter = DebugAdapter; DS.RecordArray = RecordArray; DS.FilteredRecordArray = FilteredRecordArray; DS.AdapterPopulatedRecordArray = AdapterPopulatedRecordArray; DS.ManyArray = ManyArray; DS.RecordArrayManager = RecordArrayManager; DS.RESTAdapter = RESTAdapter; DS.FixtureAdapter = FixtureAdapter; DS.RESTSerializer = RESTSerializer; DS.JSONSerializer = JSONSerializer; DS.Transform = Transform; DS.DateTransform = DateTransform; DS.StringTransform = StringTransform; DS.NumberTransform = NumberTransform; DS.BooleanTransform = BooleanTransform; DS.ActiveModelAdapter = ActiveModelAdapter; DS.ActiveModelSerializer = ActiveModelSerializer; DS.EmbeddedRecordsMixin = EmbeddedRecordsMixin; DS.belongsTo = belongsTo; DS.hasMany = hasMany; DS.ContainerProxy = ContainerProxy; DS._setupContainer = setupContainer; Ember.lookup.DS = DS; __exports__["default"] = DS; }); define("ember-data/lib/serializers", ["./serializers/json_serializer","./serializers/rest_serializer","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var JSONSerializer = __dependency1__["default"]; var RESTSerializer = __dependency2__["default"]; __exports__.JSONSerializer = JSONSerializer; __exports__.RESTSerializer = RESTSerializer; }); define("ember-data/lib/serializers/json_serializer", ["../system/changes","exports"], function(__dependency1__, __exports__) { "use strict"; var RelationshipChange = __dependency1__.RelationshipChange; var get = Ember.get, set = Ember.set, isNone = Ember.isNone, map = Ember.ArrayPolyfills.map; /** In Ember Data a Serializer is used to serialize and deserialize records when they are transferred in and out of an external source. This process involves normalizing property names, transforming attribute values and serializing relationships. For maximum performance Ember Data recommends you use the [RESTSerializer](DS.RESTSerializer.html) or one of its subclasses. `JSONSerializer` is useful for simpler or legacy backends that may not support the http://jsonapi.org/ spec. @class JSONSerializer @namespace DS */ var JSONSerializer = Ember.Object.extend({ /** The primaryKey is used when serializing and deserializing data. Ember Data always uses the `id` property to store the id of the record. The external source may not always follow this convention. In these cases it is useful to override the primaryKey property to match the primaryKey of your external store. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ primaryKey: '_id' }); ``` @property primaryKey @type {String} @default 'id' */ primaryKey: 'id', /** The `attrs` object can be used to declare a simple mapping between property names on `DS.Model` records and payload keys in the serialized JSON object representing the record. An object with the propery `key` can also be used to designate the attribute's key on the response payload. Example ```javascript App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string'), admin: DS.attr('boolean') }); App.PersonSerializer = DS.JSONSerializer.extend({ attrs: { admin: 'is_admin', occupation: {key: 'career'} } }); ``` @property attrs @type {Object} */ /** Given a subclass of `DS.Model` and a JSON object this method will iterate through each attribute of the `DS.Model` and invoke the `DS.Transform#deserialize` method on the matching property of the JSON object. This method is typically called after the serializer's `normalize` method. @method applyTransforms @private @param {subclass of DS.Model} type @param {Object} data The data to transform @return {Object} data The transformed data object */ applyTransforms: function(type, data) { type.eachTransformedAttribute(function(key, type) { var transform = this.transformFor(type); data[key] = transform.deserialize(data[key]); }, this); return data; }, /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ normalize: function(type, hash) { var fields = Ember.get(type, 'fields'); fields.forEach(function(field) { var payloadField = Ember.String.underscore(field); if (field === payloadField) { return; } hash[field] = hash[payloadField]; delete hash[payloadField]; }); return this._super.apply(this, arguments); } }); ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @return {Object} */ normalize: function(type, hash) { if (!hash) { return hash; } this.normalizeId(hash); this.normalizeUsingDeclaredMapping(type, hash); this.applyTransforms(type, hash); return hash; }, /** @method normalizeUsingDeclaredMapping @private */ normalizeUsingDeclaredMapping: function(type, hash) { var attrs = get(this, 'attrs'), payloadKey, key; if (attrs) { for (key in attrs) { payloadKey = attrs[key]; if (payloadKey && payloadKey.key) { payloadKey = payloadKey.key; } if (typeof payloadKey === 'string') { hash[key] = hash[payloadKey]; delete hash[payloadKey]; } } } }, /** @method normalizeId @private */ normalizeId: function(hash) { var primaryKey = get(this, 'primaryKey'); if (primaryKey === 'id') { return; } hash.id = hash[primaryKey]; delete hash[primaryKey]; }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```javascript App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```javascript { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(post, options) { var json = { POST_TTL: post.get('title'), POST_BDY: post.get('body'), POST_CMS: post.get('comments').mapProperty('id') } if (options.includeId) { json.POST_ID_ = post.get('id'); } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachAttribute(function(name) { json[serverAttributeName(name)] = record.get(name); }) record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = record.get(name).mapBy('id'); } }); if (options.includeId) { json.ID_ = record.get('id'); } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```javascript { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(record, options) { var json = this._super.apply(this, arguments); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {subclass of DS.Model} record @param {Object} options @return {Object} json */ serialize: function(record, options) { var json = {}; if (options && options.includeId) { var id = get(record, 'id'); if (id) { json[get(this, 'primaryKey')] = id; } } record.eachAttribute(function(key, attribute) { this.serializeAttribute(record, json, key, attribute); }, this); record.eachRelationship(function(key, relationship) { if (relationship.kind === 'belongsTo') { this.serializeBelongsTo(record, json, relationship); } else if (relationship.kind === 'hasMany') { this.serializeHasMany(record, json, relationship); } }, this); return json; }, /** `serializeAttribute` can be used to customize how `DS.attr` properties are serialized For example if you wanted to ensure all your attributes were always serialized as properties on an `attributes` object you could write: ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serializeAttribute: function(record, json, key, attributes) { json.attributes = json.attributes || {}; this._super(record, json.attributes, key, attributes); } }); ``` @method serializeAttribute @param {DS.Model} record @param {Object} json @param {String} key @param {Object} attribute */ serializeAttribute: function(record, json, key, attribute) { var attrs = get(this, 'attrs'); var value = get(record, key), type = attribute.type; if (type) { var transform = this.transformFor(type); value = transform.serialize(value); } // if provided, use the mapping provided by `attrs` in // the serializer key = attrs && attrs[key] || (this.keyForAttribute ? this.keyForAttribute(key) : key); json[key] = value; }, /** `serializeBelongsTo` can be used to customize how `DS.belongsTo` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeBelongsTo: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.toJSON(); } }); ``` @method serializeBelongsTo @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeBelongsTo: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; if (isNone(belongsTo)) { json[key] = belongsTo; } else { json[key] = get(belongsTo, 'id'); } if (relationship.options.polymorphic) { this.serializePolymorphicType(record, json, relationship); } }, /** `serializeHasMany` can be used to customize how `DS.hasMany` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeHasMany: function(record, json, relationship) { var key = relationship.key; if (key === 'comments') { return; } else { this._super.apply(this, arguments); } } }); ``` @method serializeHasMany @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeHasMany: function(record, json, relationship) { var key = relationship.key; var payloadKey = this.keyForRelationship ? this.keyForRelationship(key, "hasMany") : key; var relationshipType = RelationshipChange.determineRelationshipType(record.constructor, relationship); if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') { json[payloadKey] = get(record, key).mapBy('id'); // TODO support for polymorphic manyToNone and manyToMany relationships } }, /** You can use this method to customize how polymorphic objects are serialized. Objects are considered to be polymorphic if `{polymorphic: true}` is pass as the second argument to the `DS.belongsTo` function. Example ```javascript App.CommentSerializer = DS.JSONSerializer.extend({ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; json[key + "_type"] = belongsTo.constructor.typeKey; } }); ``` @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializePolymorphicType: Ember.K, // EXTRACT /** The `extract` method is used to deserialize payload data from the server. By default the `JSONSerializer` does not push the records into the store. However records that subclass `JSONSerializer` such as the `RESTSerializer` may push records into the store as part of the extract call. This method delegates to a more specific extract method based on the `requestType`. Example ```javascript var get = Ember.get; socket.on('message', function(message) { var modelName = message.model; var data = message.data; var type = store.modelFor(modelName); var serializer = store.serializerFor(type.typeKey); var record = serializer.extract(store, type, data, get(data, 'id'), 'single'); store.push(modelName, record); }); ``` @method extract @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extract: function(store, type, payload, id, requestType) { this.extractMeta(store, type, payload); var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1); return this[specificExtract](store, type, payload, id, requestType); }, /** `extractFindAll` is a hook into the extract method used when a call is made to `DS.Store#findAll`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindAll @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindAll: function(store, type, payload){ return this.extractArray(store, type, payload); }, /** `extractFindQuery` is a hook into the extract method used when a call is made to `DS.Store#findQuery`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindQuery: function(store, type, payload){ return this.extractArray(store, type, payload); }, /** `extractFindMany` is a hook into the extract method used when a call is made to `DS.Store#findMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindMany: function(store, type, payload){ return this.extractArray(store, type, payload); }, /** `extractFindHasMany` is a hook into the extract method used when a call is made to `DS.Store#findHasMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindHasMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindHasMany: function(store, type, payload){ return this.extractArray(store, type, payload); }, /** `extractCreateRecord` is a hook into the extract method used when a call is made to `DS.Store#createRecord`. By default this method is alias for [extractSave](#method_extractSave). @method extractCreateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractCreateRecord: function(store, type, payload) { return this.extractSave(store, type, payload); }, /** `extractUpdateRecord` is a hook into the extract method used when a call is made to `DS.Store#update`. By default this method is alias for [extractSave](#method_extractSave). @method extractUpdateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractUpdateRecord: function(store, type, payload) { return this.extractSave(store, type, payload); }, /** `extractDeleteRecord` is a hook into the extract method used when a call is made to `DS.Store#deleteRecord`. By default this method is alias for [extractSave](#method_extractSave). @method extractDeleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractDeleteRecord: function(store, type, payload) { return this.extractSave(store, type, payload); }, /** `extractFind` is a hook into the extract method used when a call is made to `DS.Store#find`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFind @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractFind: function(store, type, payload) { return this.extractSingle(store, type, payload); }, /** `extractFindBelongsTo` is a hook into the extract method used when a call is made to `DS.Store#findBelongsTo`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFindBelongsTo @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractFindBelongsTo: function(store, type, payload) { return this.extractSingle(store, type, payload); }, /** `extractSave` is a hook into the extract method used when a call is made to `DS.Model#save`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractSave @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractSave: function(store, type, payload) { return this.extractSingle(store, type, payload); }, /** `extractSingle` is used to deserialize a single record returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractSingle: function(store, type, payload) { payload.comments = payload._embedded.comment; delete payload._embedded; return this._super(store, type, payload); }, }); ``` @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractSingle: function(store, type, payload) { return this.normalize(type, payload); }, /** `extractArray` is used to deserialize an array of records returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractArray: function(store, type, payload) { return payload.map(function(json) { return this.extractSingle(store, type, json); }, this); } }); ``` @method extractArray @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractArray: function(store, type, arrayPayload) { var serializer = this; return map.call(arrayPayload, function(singlePayload) { return serializer.normalize(type, singlePayload); }); }, /** `extractMeta` is used to deserialize any meta information in the adapter payload. By default Ember Data expects meta information to be located on the `meta` property of the payload object. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractMeta: function(store, type, payload) { if (payload && payload._pagination) { store.metaForType(type, payload._pagination); delete payload._pagination; } } }); ``` @method extractMeta @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload */ extractMeta: function(store, type, payload) { if (payload && payload.meta) { store.metaForType(type, payload.meta); delete payload.meta; } }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. Example ```javascript App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @return {String} normalized key */ /** `keyForRelationship` can be used to define a custom key when serializing relationship properties. By default `JSONSerializer` does not provide an implementation of this method. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ keyForRelationship: function(key, relationship) { return 'rel_' + Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} relationship type @return {String} normalized key */ // HELPERS /** @method transformFor @private @param {String} attributeType @param {Boolean} skipAssertion @return {DS.Transform} transform */ transformFor: function(attributeType, skipAssertion) { var transform = this.container.lookup('transform:' + attributeType); return transform; } }); __exports__["default"] = JSONSerializer; }); define("ember-data/lib/serializers/rest_serializer", ["./json_serializer","ember-inflector/lib/system/string","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var JSONSerializer = __dependency1__["default"]; var get = Ember.get, set = Ember.set; var forEach = Ember.ArrayPolyfills.forEach; var map = Ember.ArrayPolyfills.map; var singularize = __dependency2__.singularize; var camelize = Ember.String.camelize; function coerceId(id) { return id == null ? null : id+''; } /** Normally, applications will use the `RESTSerializer` by implementing the `normalize` method and individual normalizations under `normalizeHash`. This allows you to do whatever kind of munging you need, and is especially useful if your server is inconsistent and you need to do munging differently for many different kinds of responses. See the `normalize` documentation for more information. ## Across the Board Normalization There are also a number of hooks that you might find useful to defined across-the-board rules for your payload. These rules will be useful if your server is consistent, or if you're building an adapter for an infrastructure service, like Parse, and want to encode service conventions. For example, if all of your keys are underscored and all-caps, but otherwise consistent with the names you use in your models, you can implement across-the-board rules for how to convert an attribute name in your model to a key in your JSON. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` You can also implement `keyForRelationship`, which takes the name of the relationship as the first parameter, and the kind of relationship (`hasMany` or `belongsTo`) as the second parameter. @class RESTSerializer @namespace DS @extends DS.JSONSerializer */ var RESTSerializer = JSONSerializer.extend({ /** If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, given the following json where the the `IDs` under `"comments"` are provided as `_id` instead of `id`. ```javascript { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "_id": 1, "body": "FIRST" }, { "_id": 2, "body": "Rails is unagi" }] } ``` You use `normalizeHash` to normalize just the comments: ```javascript App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is usually just the original key that was in the original payload. However, key names will be impacted by any modifications done in the `normalizePayload` method. The `DS.RESTSerializer`'s default implementation makes no changes to the payload keys. @property normalizeHash @type {Object} @default undefined */ /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. For example, if you have a payload that looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "id": 1, "body": "FIRST" }, { "id": 2, "body": "Rails is unagi" }] } ``` The `normalize` method will be called three times: * With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }` * With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }` * With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }` You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, if the `IDs` under `"comments"` are provided as `_id` instead of `id`, you can specify how to normalize just the comments: ```js App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is just the original key that was in the original payload. @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @return {Object} */ normalize: function(type, hash, prop) { this.normalizeId(hash); this.normalizeAttributes(type, hash); this.normalizeRelationships(type, hash); this.normalizeUsingDeclaredMapping(type, hash); if (this.normalizeHash && this.normalizeHash[prop]) { this.normalizeHash[prop](hash); } this.applyTransforms(type, hash); return hash; }, /** You can use this method to normalize all payloads, regardless of whether they represent single records or an array. For example, you might want to remove some extraneous data from the payload: ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ normalizePayload: function(payload) { delete payload.version; delete payload.status; return payload; } }); ``` @method normalizePayload @param {Object} payload @return {Object} the normalized payload */ normalizePayload: function(payload) { return payload; }, /** @method normalizeAttributes @private */ normalizeAttributes: function(type, hash) { var payloadKey, key; if (this.keyForAttribute) { type.eachAttribute(function(key) { payloadKey = this.keyForAttribute(key); if (key === payloadKey) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { var payloadKey, key; if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { payloadKey = this.keyForRelationship(key, relationship.kind); if (key === payloadKey) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** Called when the server has returned a payload representing a single record, such as in response to a `find` or `save`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for post 1: ```js { "id": 1, "title": "Rails is omakase", "_embedded": { "comment": [{ "_id": 1, "comment_title": "FIRST" }, { "_id": 2, "comment_title": "Rails is unagi" }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type extractSingle: function(store, type, payload, id) { var comments = payload._embedded.comment; delete payload._embedded; payload = { comments: comments, post: payload }; return this._super(store, type, payload, id); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractSingle`, the built-in implementation will find the primary record in your normalized payload and push the remaining records into the store. The primary record is the single hash found under `post` or the first element of the `posts` array. The primary record has special meaning when the record is being created for the first time or updated (`createRecord` or `updateRecord`). In particular, it will update the properties of the record that was saved. @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} primaryType @param {Object} payload @param {String} recordId @return {Object} the primary response to the original request */ extractSingle: function(store, primaryType, payload, recordId) { payload = this.normalizePayload(payload); var primaryTypeName = primaryType.typeKey, primaryRecord; for (var prop in payload) { var typeName = this.typeForRoot(prop), type = store.modelFor(typeName), isPrimary = type.typeKey === primaryTypeName; // legacy support for singular resources if (isPrimary && Ember.typeOf(payload[prop]) !== "array" ) { primaryRecord = this.normalize(primaryType, payload[prop], prop); continue; } /*jshint loopfunc:true*/ forEach.call(payload[prop], function(hash) { var typeName = this.typeForRoot(prop), type = store.modelFor(typeName), typeSerializer = store.serializerFor(type); hash = typeSerializer.normalize(type, hash, prop); var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord, isUpdatedRecord = isPrimary && coerceId(hash.id) === recordId; // find the primary record. // // It's either: // * the record with the same ID as the original request // * in the case of a newly created record that didn't have an ID, the first // record in the Array if (isFirstCreatedRecord || isUpdatedRecord) { primaryRecord = hash; } else { store.push(typeName, hash); } }, this); } return primaryRecord; }, /** Called when the server has returned a payload representing multiple records, such as in response to a `findAll` or `findQuery`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for all posts: ```js { "_embedded": { "post": [{ "id": 1, "title": "Rails is omakase" }, { "id": 2, "title": "The Parley Letter" }], "comment": [{ "_id": 1, "comment_title": "Rails is unagi" "post_id": 1 }, { "_id": 2, "comment_title": "Don't tread on me", "post_id": 2 }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type // and the comments are listed under a post's `comments` key. extractArray: function(store, type, payload) { var posts = payload._embedded.post; var comments = []; var postCache = {}; posts.forEach(function(post) { post.comments = []; postCache[post.id] = post; }); payload._embedded.comment.forEach(function(comment) { comments.push(comment); postCache[comment.post_id].comments.push(comment); delete comment.post_id; } payload = { comments: comments, posts: payload }; return this._super(store, type, payload); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractArray`, the built-in implementation will find the primary array in your normalized payload and push the remaining records into the store. The primary array is the array found under `posts`. The primary record has special meaning when responding to `findQuery` or `findHasMany`. In particular, the primary array will become the list of records in the record array that kicked off the request. If your primary array contains secondary (embedded) records of the same type, you cannot place these into the primary array `posts`. Instead, place the secondary items into an underscore prefixed property `_posts`, which will push these items into the store and will not affect the resulting query. @method extractArray @param {DS.Store} store @param {subclass of DS.Model} primaryType @param {Object} payload @return {Array} The primary array that was returned in response to the original query. */ extractArray: function(store, primaryType, payload) { payload = this.normalizePayload(payload); var primaryTypeName = primaryType.typeKey, primaryArray; for (var prop in payload) { var typeKey = prop, forcedSecondary = false; if (prop.charAt(0) === '_') { forcedSecondary = true; typeKey = prop.substr(1); } var typeName = this.typeForRoot(typeKey), type = store.modelFor(typeName), typeSerializer = store.serializerFor(type), isPrimary = (!forcedSecondary && (type.typeKey === primaryTypeName)); /*jshint loopfunc:true*/ var normalizedArray = map.call(payload[prop], function(hash) { return typeSerializer.normalize(type, hash, prop); }, this); if (isPrimary) { primaryArray = normalizedArray; } else { store.pushMany(typeName, normalizedArray); } } return primaryArray; }, /** This method allows you to push a payload containing top-level collections of records organized per type. ```js { "posts": [{ "id": "1", "title": "Rails is omakase", "author", "1", "comments": [ "1" ] }], "comments": [{ "id": "1", "body": "FIRST" }], "users": [{ "id": "1", "name": "@d2h" }] } ``` It will first normalize the payload, so you can use this to push in data streaming in from your server structured the same way that fetches and saves are structured. @method pushPayload @param {DS.Store} store @param {Object} payload */ pushPayload: function(store, payload) { payload = this.normalizePayload(payload); for (var prop in payload) { var typeName = this.typeForRoot(prop), type = store.modelFor(typeName), typeSerializer = store.serializerFor(type); /*jshint loopfunc:true*/ var normalizedArray = map.call(Ember.makeArray(payload[prop]), function(hash) { return typeSerializer.normalize(type, hash, prop); }, this); store.pushMany(typeName, normalizedArray); } }, /** This method is used to convert each JSON root key in the payload into a typeKey that it can use to look up the appropriate model for that part of the payload. By default the typeKey for a model is its name in camelCase, so if your JSON root key is 'fast-car' you would use typeForRoot to convert it to 'fastCar' so that Ember Data finds the `FastCar` model. If you diverge from this norm you should also consider changes to store._normalizeTypeKey as well. For example, your server may return prefixed root keys like so: ```js { "response-fast-car": { "id": "1", "name": "corvette" } } ``` In order for Ember Data to know that the model corresponding to the 'response-fast-car' hash is `FastCar` (typeKey: 'fastCar'), you can override typeForRoot to convert 'response-fast-car' to 'fastCar' like so: ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ typeForRoot: function(root) { // 'response-fast-car' should become 'fast-car' var subRoot = root.substring(9); // _super normalizes 'fast-car' to 'fastCar' return this._super(subRoot); } }); ``` @method typeForRoot @param {String} key @return {String} the model's typeKey */ typeForRoot: function(key) { return camelize(singularize(key)); }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```js App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```js { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(post, options) { var json = { POST_TTL: post.get('title'), POST_BDY: post.get('body'), POST_CMS: post.get('comments').mapProperty('id') } if (options.includeId) { json.POST_ID_ = post.get('id'); } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachAttribute(function(name) { json[serverAttributeName(name)] = record.get(name); }) record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = record.get(name).mapBy('id'); } }); if (options.includeId) { json.ID_ = record.get('id'); } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```js { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = this._super(record, options); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param record @param options */ serialize: function(record, options) { return this._super.apply(this, arguments); }, /** You can use this method to customize the root keys serialized into the JSON. By default the REST Serializer sends the typeKey of a model, whih is a camelized version of the name. For example, your server may expect underscored root objects. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(hash, type, record, options) { hash[type.typeKey] = this.serialize(record, options); }, /** You can use this method to customize how polymorphic objects are serialized. By default the JSON Serializer creates the key by appending `Type` to the attribute and value from the model's camelcased model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; json[key + "Type"] = belongsTo.constructor.typeKey; } }); __exports__["default"] = RESTSerializer; }); define("ember-data/lib/setup-container", ["./initializers/store","./initializers/transforms","./initializers/store_injections","./initializers/data_adapter","../../../activemodel-adapter/lib/setup-container","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { "use strict"; var initializeStore = __dependency1__["default"]; var initializeTransforms = __dependency2__["default"]; var initializeStoreInjections = __dependency3__["default"]; var initializeDataAdapter = __dependency4__["default"]; var setupActiveModelContainer = __dependency5__["default"]; __exports__["default"] = function setupContainer(container, application){ // application is not a required argument. This ensures // testing setups can setup a container without booting an // entire ember application. initializeDataAdapter(container, application); initializeTransforms(container, application); initializeStoreInjections(container, application); initializeStore(container, application); setupActiveModelContainer(container, application); }; }); define("ember-data/lib/system/adapter", ["exports"], function(__exports__) { "use strict"; /** @module ember-data */ var get = Ember.get, set = Ember.set; var map = Ember.ArrayPolyfills.map; var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; /** A `DS.InvalidError` is used by an adapter to signal the external API was unable to process a request because the content was not semantically correct or meaningful per the API. Usually this means a record failed some form of server side validation. When a promise from an adapter is rejected with a `DS.InvalidError` the record will transition to the `invalid` state and the errors will be set to the `errors` property on the record. Example ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"]; return new DS.InvalidError(jsonErrors); } else { return error; } } }); ``` The `DS.InvalidError` must be constructed with a single object whose keys are the invalid model properties, and whose values are the corresponding error messages. For example: ```javascript return new DS.InvalidError({ length: 'Must be less than 15', name: 'Must not be blank }); ``` @class InvalidError @namespace DS */ var InvalidError = function(errors) { var tmp = Error.prototype.constructor.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors)); this.errors = errors; for (var i=0, l=errorProps.length; i<l; i++) { this[errorProps[i]] = tmp[errorProps[i]]; } }; InvalidError.prototype = Ember.create(Error.prototype); /** An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. Typically the adapter is not invoked directly instead its functionality is accessed through the `store`. ### Creating an Adapter Create a new subclass of `DS.Adapter`, then assign it to the `ApplicationAdapter` property of the application. ```javascript var MyAdapter = DS.Adapter.extend({ // ...your code here }); App.ApplicationAdapter = MyAdapter; ``` Model-specific adapters can be created by assigning your adapter class to the `ModelName` + `Adapter` property of the application. ```javascript var MyPostAdapter = DS.Adapter.extend({ // ...Post-specific adapter code goes here }); App.PostAdapter = MyPostAdapter; ``` `DS.Adapter` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `find()` * `createRecord()` * `updateRecord()` * `deleteRecord()` * `findAll()` * `findQuery()` To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods: * `findMany()` For an example implementation, see `DS.RESTAdapter`, the included REST adapter. @class Adapter @namespace DS @extends Ember.Object */ var Adapter = Ember.Object.extend({ /** If you would like your adapter to use a custom serializer you can set the `defaultSerializer` property to be the name of the custom serializer. Note the `defaultSerializer` serializer has a lower priority then a model specific serializer (i.e. `PostSerializer`) or the `application` serializer. ```javascript var DjangoAdapter = DS.Adapter.extend({ defaultSerializer: 'django' }); ``` @property defaultSerializer @type {String} */ /** The `find()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `find()` being called, you should query your persistence layer for a record with the given ID. Once found, you can asynchronously call the store's `push()` method to push the record into the store. Here is an example `find` implementation: ```javascript App.ApplicationAdapter = DS.Adapter.extend({ find: function(store, type, id) { var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @return {Promise} promise */ find: Ember.required(Function), /** The `findAll()` method is called when you call `find` on the store without an ID (i.e. `store.find('post')`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findAll: function(store, type, sinceToken) { var url = type; var query = { since: sinceToken }; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: null, /** This method is called when you call `find` on the store with a query object as the second parameter (i.e. `store.find('person', { page: 1 })`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findQuery: function(store, type, query) { var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: null, /** If the globally unique IDs for your records should be generated on the client, implement the `generateIdForRecord()` method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's `primaryKey`. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls `didCreateRecord()`. Only implement this method if you intend to generate record IDs on the client-side. The `generateIdForRecord()` method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter: ```javascript generateIdForRecord: function(store, record) { var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision(); return uuid; } ``` @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record @return {String|Number} id */ generateIdForRecord: null, /** Proxies to the serializer's `serialize` method. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var url = type; // ... } }); ``` @method serialize @param {DS.Model} record @param {Object} options @return {Object} serialized record */ serialize: function(record, options) { return get(record, 'store').serializerFor(record.constructor.typeKey).serialize(record, options); }, /** Implement this method in a subclass to handle the creation of new records. Serializes the record and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'POST', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ createRecord: Ember.required(Function), /** Implement this method in a subclass to handle the updating of a record. Serializes the record update and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ updateRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var id = record.get('id'); var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'PUT', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ updateRecord: Ember.required(Function), /** Implement this method in a subclass to handle the deletion of a record. Sends a delete request for the record to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ deleteRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var id = record.get('id'); var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'DELETE', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ deleteRecord: Ember.required(Function), /** Find multiple records at once. By default, it loops over the provided ids and calls `find` on each. May be overwritten to improve performance and reduce the number of server requests. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findMany: function(store, type, ids) { var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, {ids: ids}).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method findMany @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the records @param {Array} ids @return {Promise} promise */ findMany: function(store, type, ids) { var promises = map.call(ids, function(id) { return this.find(store, type, id); }, this); return Ember.RSVP.all(promises); } }); __exports__.InvalidError = InvalidError; __exports__.Adapter = Adapter; __exports__["default"] = Adapter; }); define("ember-data/lib/system/changes", ["./changes/relationship_change","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var RelationshipChange = __dependency1__.RelationshipChange; var RelationshipChangeAdd = __dependency1__.RelationshipChangeAdd; var RelationshipChangeRemove = __dependency1__.RelationshipChangeRemove; var OneToManyChange = __dependency1__.OneToManyChange; var ManyToNoneChange = __dependency1__.ManyToNoneChange; var OneToOneChange = __dependency1__.OneToOneChange; var ManyToManyChange = __dependency1__.ManyToManyChange; __exports__.RelationshipChange = RelationshipChange; __exports__.RelationshipChangeAdd = RelationshipChangeAdd; __exports__.RelationshipChangeRemove = RelationshipChangeRemove; __exports__.OneToManyChange = OneToManyChange; __exports__.ManyToNoneChange = ManyToNoneChange; __exports__.OneToOneChange = OneToOneChange; __exports__.ManyToManyChange = ManyToManyChange; }); define("ember-data/lib/system/changes/relationship_change", ["../model","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var Model = __dependency1__.Model; var get = Ember.get, set = Ember.set; var forEach = Ember.EnumerableUtils.forEach; /** @class RelationshipChange @namespace DS @private @constructor */ var RelationshipChange = function(options) { this.parentRecord = options.parentRecord; this.childRecord = options.childRecord; this.firstRecord = options.firstRecord; this.firstRecordKind = options.firstRecordKind; this.firstRecordName = options.firstRecordName; this.secondRecord = options.secondRecord; this.secondRecordKind = options.secondRecordKind; this.secondRecordName = options.secondRecordName; this.changeType = options.changeType; this.store = options.store; this.committed = {}; }; /** @class RelationshipChangeAdd @namespace DS @private @constructor */ var RelationshipChangeAdd = function(options){ RelationshipChange.call(this, options); }; /** @class RelationshipChangeRemove @namespace DS @private @constructor */ var RelationshipChangeRemove = function(options){ RelationshipChange.call(this, options); }; RelationshipChange.create = function(options) { return new RelationshipChange(options); }; RelationshipChangeAdd.create = function(options) { return new RelationshipChangeAdd(options); }; RelationshipChangeRemove.create = function(options) { return new RelationshipChangeRemove(options); }; var OneToManyChange = {}; var OneToNoneChange = {}; var ManyToNoneChange = {}; var OneToOneChange = {}; var ManyToManyChange = {}; RelationshipChange._createChange = function(options){ if(options.changeType === "add"){ return RelationshipChangeAdd.create(options); } if(options.changeType === "remove"){ return RelationshipChangeRemove.create(options); } }; RelationshipChange.determineRelationshipType = function(recordType, knownSide){ var knownKey = knownSide.key, key, otherKind; var knownKind = knownSide.kind; var inverse = recordType.inverseFor(knownKey); if (inverse){ key = inverse.name; otherKind = inverse.kind; } if (!inverse){ return knownKind === "belongsTo" ? "oneToNone" : "manyToNone"; } else{ if(otherKind === "belongsTo"){ return knownKind === "belongsTo" ? "oneToOne" : "manyToOne"; } else{ return knownKind === "belongsTo" ? "oneToMany" : "manyToMany"; } } }; RelationshipChange.createChange = function(firstRecord, secondRecord, store, options){ // Get the type of the child based on the child's client ID var firstRecordType = firstRecord.constructor, changeType; changeType = RelationshipChange.determineRelationshipType(firstRecordType, options); if (changeType === "oneToMany"){ return OneToManyChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToOne"){ return OneToManyChange.createChange(secondRecord, firstRecord, store, options); } else if (changeType === "oneToNone"){ return OneToNoneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToNone"){ return ManyToNoneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "oneToOne"){ return OneToOneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToMany"){ return ManyToManyChange.createChange(firstRecord, secondRecord, store, options); } }; OneToNoneChange.createChange = function(childRecord, parentRecord, store, options) { var key = options.key; var change = RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, store: store, changeType: options.changeType, firstRecordName: key, firstRecordKind: "belongsTo" }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; ManyToNoneChange.createChange = function(childRecord, parentRecord, store, options) { var key = options.key; var change = RelationshipChange._createChange({ parentRecord: childRecord, childRecord: parentRecord, secondRecord: childRecord, store: store, changeType: options.changeType, secondRecordName: options.key, secondRecordKind: "hasMany" }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; ManyToManyChange.createChange = function(childRecord, parentRecord, store, options) { // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. var key = options.key; var change = RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "hasMany", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; OneToOneChange.createChange = function(childRecord, parentRecord, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; } else if (options.key) { key = options.key; } else { } var change = RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "belongsTo", secondRecordKind: "belongsTo", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; OneToOneChange.maintainInvariant = function(options, store, childRecord, key){ if (options.changeType === "add" && store.recordIsMaterialized(childRecord)) { var oldParent = get(childRecord, key); if (oldParent){ var correspondingChange = OneToOneChange.createChange(childRecord, oldParent, store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childRecord, key, options.parentRecord , null, correspondingChange); correspondingChange.sync(); } } }; OneToManyChange.createChange = function(childRecord, parentRecord, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; OneToManyChange.maintainInvariant( options, store, childRecord, key ); } else if (options.key) { key = options.key; } else { } var change = RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "belongsTo", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, change.getSecondRecordName(), change); return change; }; OneToManyChange.maintainInvariant = function(options, store, childRecord, key){ if (options.changeType === "add" && childRecord) { var oldParent = get(childRecord, key); if (oldParent){ var correspondingChange = OneToManyChange.createChange(childRecord, oldParent, store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childRecord, key, options.parentRecord, correspondingChange.getSecondRecordName(), correspondingChange); correspondingChange.sync(); } } }; /** @class RelationshipChange @namespace DS */ RelationshipChange.prototype = { getSecondRecordName: function() { var name = this.secondRecordName, parent; if (!name) { parent = this.secondRecord; if (!parent) { return; } var childType = this.firstRecord.constructor; var inverse = childType.inverseFor(this.firstRecordName); this.secondRecordName = inverse.name; } return this.secondRecordName; }, /** Get the name of the relationship on the belongsTo side. @method getFirstRecordName @return {String} */ getFirstRecordName: function() { var name = this.firstRecordName; return name; }, /** @method destroy @private */ destroy: function() { var childRecord = this.childRecord, belongsToName = this.getFirstRecordName(), hasManyName = this.getSecondRecordName(), store = this.store; store.removeRelationshipChangeFor(childRecord, belongsToName, this.parentRecord, hasManyName, this.changeType); }, getSecondRecord: function(){ return this.secondRecord; }, /** @method getFirstRecord @private */ getFirstRecord: function() { return this.firstRecord; }, coalesce: function(){ var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecord); forEach(relationshipPairs, function(pair){ var addedChange = pair["add"]; var removedChange = pair["remove"]; if(addedChange && removedChange) { addedChange.destroy(); removedChange.destroy(); } }); } }; RelationshipChangeAdd.prototype = Ember.create(RelationshipChange.create({})); RelationshipChangeRemove.prototype = Ember.create(RelationshipChange.create({})); // the object is a value, and not a promise function isValue(object) { return typeof object === 'object' && (!object.then || typeof object.then !== 'function'); } RelationshipChangeAdd.prototype.changeType = "add"; RelationshipChangeAdd.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); if (secondRecord instanceof Model && firstRecord instanceof Model) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, firstRecord); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ var relationship = get(secondRecord, secondRecordName); if (isValue(relationship)) { relationship.addObject(firstRecord); } }); } } if (firstRecord instanceof Model && secondRecord instanceof Model && get(firstRecord, firstRecordName) !== secondRecord) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, secondRecord); }); } else if(this.firstRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ var relationship = get(firstRecord, firstRecordName); if (isValue(relationship)) { relationship.addObject(secondRecord); } }); } } this.coalesce(); }; RelationshipChangeRemove.prototype.changeType = "remove"; RelationshipChangeRemove.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); if (secondRecord instanceof Model && firstRecord instanceof Model) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, null); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ var relationship = get(secondRecord, secondRecordName); if (isValue(relationship)) { relationship.removeObject(firstRecord); } }); } } if (firstRecord instanceof Model && get(firstRecord, firstRecordName)) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, null); }); } else if(this.firstRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ var relationship = get(firstRecord, firstRecordName); if (isValue(relationship)) { relationship.removeObject(secondRecord); } }); } } this.coalesce(); }; __exports__.RelationshipChange = RelationshipChange; __exports__.RelationshipChangeAdd = RelationshipChangeAdd; __exports__.RelationshipChangeRemove = RelationshipChangeRemove; __exports__.OneToManyChange = OneToManyChange; __exports__.ManyToNoneChange = ManyToNoneChange; __exports__.OneToOneChange = OneToOneChange; __exports__.ManyToManyChange = ManyToManyChange; }); define("ember-data/lib/system/container_proxy", ["exports"], function(__exports__) { "use strict"; /** This is used internally to enable deprecation of container paths and provide a decent message to the user indicating how to fix the issue. @class ContainerProxy @namespace DS @private */ var ContainerProxy = function (container){ this.container = container; }; ContainerProxy.prototype.aliasedFactory = function(path, preLookup) { var _this = this; return {create: function(){ if (preLookup) { preLookup(); } return _this.container.lookup(path); }}; }; ContainerProxy.prototype.registerAlias = function(source, dest, preLookup) { var factory = this.aliasedFactory(dest, preLookup); return this.container.register(source, factory); }; ContainerProxy.prototype.registerDeprecation = function(deprecated, valid) { var preLookupCallback = function(){ }; return this.registerAlias(deprecated, valid, preLookupCallback); }; ContainerProxy.prototype.registerDeprecations = function(proxyPairs) { for (var i = proxyPairs.length; i > 0; i--) { var proxyPair = proxyPairs[i - 1], deprecated = proxyPair['deprecated'], valid = proxyPair['valid']; this.registerDeprecation(deprecated, valid); } }; __exports__["default"] = ContainerProxy; }); define("ember-data/lib/system/debug", ["./debug/debug_info","./debug/debug_adapter","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var DebugAdapter = __dependency2__["default"]; __exports__["default"] = DebugAdapter; }); define("ember-data/lib/system/debug/debug_adapter", ["../model","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var Model = __dependency1__.Model; var get = Ember.get, capitalize = Ember.String.capitalize, underscore = Ember.String.underscore; /** Extend `Ember.DataAdapter` with ED specific code. @class DebugAdapter @namespace DS @extends Ember.DataAdapter @private */ var DebugAdapter = Ember.DataAdapter.extend({ getFilters: function() { return [ { name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' } ]; }, detect: function(klass) { return klass !== Model && Model.detect(klass); }, columnsForType: function(type) { var columns = [{ name: 'id', desc: 'Id' }], count = 0, self = this; get(type, 'attributes').forEach(function(name, meta) { if (count++ > self.attributeLimit) { return false; } var desc = capitalize(underscore(name).replace('_', ' ')); columns.push({ name: name, desc: desc }); }); return columns; }, getRecords: function(type) { return this.get('store').all(type); }, getRecordColumnValues: function(record) { var self = this, count = 0, columnValues = { id: get(record, 'id') }; record.eachAttribute(function(key) { if (count++ > self.attributeLimit) { return false; } var value = get(record, key); columnValues[key] = value; }); return columnValues; }, getRecordKeywords: function(record) { var keywords = [], keys = Ember.A(['id']); record.eachAttribute(function(key) { keys.push(key); }); keys.forEach(function(key) { keywords.push(get(record, key)); }); return keywords; }, getRecordFilterValues: function(record) { return { isNew: record.get('isNew'), isModified: record.get('isDirty') && !record.get('isNew'), isClean: !record.get('isDirty') }; }, getRecordColor: function(record) { var color = 'black'; if (record.get('isNew')) { color = 'green'; } else if (record.get('isDirty')) { color = 'blue'; } return color; }, observeRecord: function(record, recordUpdated) { var releaseMethods = Ember.A(), self = this, keysToObserve = Ember.A(['id', 'isNew', 'isDirty']); record.eachAttribute(function(key) { keysToObserve.push(key); }); keysToObserve.forEach(function(key) { var handler = function() { recordUpdated(self.wrapRecord(record)); }; Ember.addObserver(record, key, handler); releaseMethods.push(function() { Ember.removeObserver(record, key, handler); }); }); var release = function() { releaseMethods.forEach(function(fn) { fn(); } ); }; return release; } }); __exports__["default"] = DebugAdapter; }); define("ember-data/lib/system/debug/debug_info", ["../model","exports"], function(__dependency1__, __exports__) { "use strict"; var Model = __dependency1__.Model; Model.reopen({ /** Provides info about the model for debugging purposes by grouping the properties into more semantic groups. Meant to be used by debugging tools such as the Chrome Ember Extension. - Groups all attributes in "Attributes" group. - Groups all belongsTo relationships in "Belongs To" group. - Groups all hasMany relationships in "Has Many" group. - Groups all flags in "Flags" group. - Flags relationship CPs as expensive properties. @method _debugInfo @for DS.Model @private */ _debugInfo: function() { var attributes = ['id'], relationships = { belongsTo: [], hasMany: [] }, expensiveProperties = []; this.eachAttribute(function(name, meta) { attributes.push(name); }, this); this.eachRelationship(function(name, relationship) { relationships[relationship.kind].push(name); expensiveProperties.push(name); }); var groups = [ { name: 'Attributes', properties: attributes, expand: true }, { name: 'Belongs To', properties: relationships.belongsTo, expand: true }, { name: 'Has Many', properties: relationships.hasMany, expand: true }, { name: 'Flags', properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid'] } ]; return { propertyInfo: { // include all other mixins / properties (not just the grouped ones) includeOtherProperties: true, groups: groups, // don't pre-calculate unless cached expensiveProperties: expensiveProperties } }; } }); __exports__["default"] = Model; }); define("ember-data/lib/system/model", ["./model/model","./model/attributes","./model/states","./model/errors","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; /** @module ember-data */ var Model = __dependency1__["default"]; var attr = __dependency2__["default"]; var RootState = __dependency3__["default"]; var Errors = __dependency4__["default"]; __exports__.Model = Model; __exports__.RootState = RootState; __exports__.attr = attr; __exports__.Errors = Errors; }); define("ember-data/lib/system/model/attributes", ["./model","exports"], function(__dependency1__, __exports__) { "use strict"; var Model = __dependency1__["default"]; /** @module ember-data */ var get = Ember.get; /** @class Model @namespace DS */ Model.reopenClass({ /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are the meta object for the property. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); var attributes = Ember.get(App.Person, 'attributes') attributes.forEach(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @property attributes @static @type {Ember.Map} @readOnly */ attributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isAttribute) { meta.name = name; map.set(name, meta); } }); return map; }), /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); var transformedAttributes = Ember.get(App.Person, 'transformedAttributes') transformedAttributes.forEach(function(field, type) { console.log(field, type); }); // prints: // lastName string // birthday date ``` @property transformedAttributes @static @type {Ember.Map} @readOnly */ transformedAttributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachAttribute(function(key, meta) { if (meta.type) { map.set(key, meta.type); } }); return map; }), /** Iterates through the attributes of the model, calling the passed function on each attribute. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, meta); ``` - `name` the name of the current property in the iteration - `meta` the meta object for the attribute property in the iteration Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); App.Person.eachAttribute(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @method eachAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachAttribute: function(callback, binding) { get(this, 'attributes').forEach(function(name, meta) { callback.call(binding, name, meta); }, binding); }, /** Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, type); ``` - `name` the name of the current property in the iteration - `type` a string containing the name of the type of transformed applied to the attribute Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); App.Person.eachTransformedAttribute(function(name, type) { console.log(name, type); }); // prints: // lastName string // birthday date ``` @method eachTransformedAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachTransformedAttribute: function(callback, binding) { get(this, 'transformedAttributes').forEach(function(name, type) { callback.call(binding, name, type); }); } }); Model.reopen({ eachAttribute: function(callback, binding) { this.constructor.eachAttribute(callback, binding); } }); function getDefaultValue(record, options, key) { if (typeof options.defaultValue === "function") { return options.defaultValue.apply(null, arguments); } else { return options.defaultValue; } } function hasValue(record, key) { return record._attributes.hasOwnProperty(key) || record._inFlightAttributes.hasOwnProperty(key) || record._data.hasOwnProperty(key); } function getValue(record, key) { if (record._attributes.hasOwnProperty(key)) { return record._attributes[key]; } else if (record._inFlightAttributes.hasOwnProperty(key)) { return record._inFlightAttributes[key]; } else { return record._data[key]; } } /** `DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed. Ember Data ships with four basic transform types: `string`, `number`, `boolean` and `date`. You can define your own transforms by subclassing [DS.Transform](/api/data/classes/DS.Transform.html). Note that you cannot use `attr` to define an attribute of `id`. `DS.attr` takes an optional hash as a second parameter, currently supported options are: - `defaultValue`: Pass a string or a function to be called to set the attribute to a default value if none is supplied. Example ```javascript var attr = DS.attr; App.User = DS.Model.extend({ username: attr('string'), email: attr('string'), verified: attr('boolean', {defaultValue: false}) }); ``` @namespace @method attr @for DS @param {String} type the attribute type @param {Object} options a hash of options @return {Attribute} */ function attr(type, options) { options = options || {}; var meta = { type: type, isAttribute: true, options: options }; return Ember.computed('data', function(key, value) { if (arguments.length > 1) { var oldValue = getValue(this, key); if (value !== oldValue) { // Add the new value to the changed attributes hash; it will get deleted by // the 'didSetProperty' handler if it is no different from the original value this._attributes[key] = value; this.send('didSetProperty', { name: key, oldValue: oldValue, originalValue: this._data[key], value: value }); } return value; } else if (hasValue(this, key)) { return getValue(this, key); } else { return getDefaultValue(this, options, key); } // `data` is never set directly. However, it may be // invalidated from the state manager's setData // event. }).meta(meta); } __exports__["default"] = attr; }); define("ember-data/lib/system/model/errors", ["exports"], function(__exports__) { "use strict"; var get = Ember.get, isEmpty = Ember.isEmpty; var map = Ember.EnumerableUtils.map; /** @module ember-data */ /** Holds validation errors for a given record organized by attribute names. Every DS.Model has an `errors` property that is an instance of `DS.Errors`. This can be used to display validation error messages returned from the server when a `record.save()` rejects. For Example, if you had an `User` model that looked like this: ```javascript App.User = DS.Model.extend({ username: attr('string'), email: attr('string') }); ``` And you attempted to save a record that did not validate on the backend. ```javascript var user = store.createRecord('user', { username: 'tomster', email: 'invalidEmail' }); user.save(); ``` Your backend data store might return a response that looks like this. This response will be used to populate the error object. ```javascript { "errors": { "username": ["This username is already taken!"], "email": ["Doesn't look like a valid email."] } } ``` Errors can be displayed to the user by accessing their property name or using the `messages` property to get an array of all errors. ```handlebars {{#each errors.messages}} <div class="error"> {{message}} </div> {{/each}} <label>Username: {{input value=username}} </label> {{#each errors.username}} <div class="error"> {{message}} </div> {{/each}} <label>Email: {{input value=email}} </label> {{#each errors.email}} <div class="error"> {{message}} </div> {{/each}} ``` @class Errors @namespace DS @extends Ember.Object @uses Ember.Enumerable @uses Ember.Evented */ var Errors = Ember.Object.extend(Ember.Enumerable, Ember.Evented, { /** Register with target handler @method registerHandlers @param {Object} target @param {Function} becameInvalid @param {Function} becameValid */ registerHandlers: function(target, becameInvalid, becameValid) { this.on('becameInvalid', target, becameInvalid); this.on('becameValid', target, becameValid); }, /** @property errorsByAttributeName @type {Ember.MapWithDefault} @private */ errorsByAttributeName: Ember.reduceComputed("content", { initialValue: function() { return Ember.MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); }, addedItem: function(errors, error) { errors.get(error.attribute).pushObject(error); return errors; }, removedItem: function(errors, error) { errors.get(error.attribute).removeObject(error); return errors; } }), /** Returns errors for a given attribute ```javascript var user = store.createRecord('user', { username: 'tomster', email: 'invalidEmail' }); user.save().catch(function(){ user.get('errors').errorsFor('email'); // ["Doesn't look like a valid email."] }); ``` @method errorsFor @param {String} attribute @return {Array} */ errorsFor: function(attribute) { return get(this, 'errorsByAttributeName').get(attribute); }, /** An array containing all of the error messages for this record. This is useful for displaying all errors to the user. ```handlebars {{#each errors.messages}} <div class="error"> {{message}} </div> {{/each}} ``` @property messages @type {Array} */ messages: Ember.computed.mapBy('content', 'message'), /** @property content @type {Array} @private */ content: Ember.computed(function() { return Ember.A(); }), /** @method unknownProperty @private */ unknownProperty: function(attribute) { var errors = this.errorsFor(attribute); if (isEmpty(errors)) { return null; } return errors; }, /** @method nextObject @private */ nextObject: function(index, previousObject, context) { return get(this, 'content').objectAt(index); }, /** Total number of errors. @property length @type {Number} @readOnly */ length: Ember.computed.oneWay('content.length').readOnly(), /** @property isEmpty @type {Boolean} @readOnly */ isEmpty: Ember.computed.not('length').readOnly(), /** Adds error messages to a given attribute and sends `becameInvalid` event to the record. Example: ```javascript if (!user.get('username') { user.get('errors').add('username', 'This field is required'); } ``` @method add @param {String} attribute @param {Array|String} messages */ add: function(attribute, messages) { var wasEmpty = get(this, 'isEmpty'); messages = this._findOrCreateMessages(attribute, messages); get(this, 'content').addObjects(messages); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (wasEmpty && !get(this, 'isEmpty')) { this.trigger('becameInvalid'); } }, /** @method _findOrCreateMessages @private */ _findOrCreateMessages: function(attribute, messages) { var errors = this.errorsFor(attribute); return map(Ember.makeArray(messages), function(message) { return errors.findBy('message', message) || { attribute: attribute, message: message }; }); }, /** Removes all error messages from the given attribute and sends `becameValid` event to the record if there no more errors left. Example: ```javascript App.User = DS.Model.extend({ email: DS.attr('string'), twoFactorAuth: DS.attr('boolean'), phone: DS.attr('string') }); App.UserEditRoute = Ember.Route.extend({ actions: { save: function(user) { if (!user.get('twoFactorAuth')) { user.get('errors').remove('phone'); } user.save(); } } }); ``` @method remove @param {String} attribute */ remove: function(attribute) { if (get(this, 'isEmpty')) { return; } var content = get(this, 'content').rejectBy('attribute', attribute); get(this, 'content').setObjects(content); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (get(this, 'isEmpty')) { this.trigger('becameValid'); } }, /** Removes all error messages and sends `becameValid` event to the record. Example: ```javascript App.UserEditRoute = Ember.Route.extend({ actions: { retrySave: function(user) { user.get('errors').clear(); user.save(); } } }); ``` @method clear */ clear: function() { if (get(this, 'isEmpty')) { return; } get(this, 'content').clear(); this.enumerableContentDidChange(); this.trigger('becameValid'); }, /** Checks if there is error messages for the given attribute. ```javascript App.UserEditRoute = Ember.Route.extend({ actions: { save: function(user) { if (user.get('errors').has('email')) { return alert('Please update your email before attempting to save.'); } user.save(); } } }); ``` @method has @param {String} attribute @return {Boolean} true if there some errors on given attribute */ has: function(attribute) { return !isEmpty(this.errorsFor(attribute)); } }); __exports__["default"] = Errors; }); define("ember-data/lib/system/model/model", ["./states","./errors","../store","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var RootState = __dependency1__["default"]; var Errors = __dependency2__["default"]; var PromiseObject = __dependency3__.PromiseObject; /** @module ember-data */ var get = Ember.get, set = Ember.set, merge = Ember.merge, Promise = Ember.RSVP.Promise; var JSONSerializer; var retrieveFromCurrentState = Ember.computed('currentState', function(key, value) { return get(get(this, 'currentState'), key); }).readOnly(); /** The model class that all Ember Data records descend from. @class Model @namespace DS @extends Ember.Object @uses Ember.Evented */ var Model = Ember.Object.extend(Ember.Evented, { _recordArrays: undefined, _relationships: undefined, _loadingRecordArrays: undefined, /** If this property is `true` the record is in the `empty` state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the `loading` state if data needs to be fetched from the server or the `created` state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record. @property isEmpty @type {Boolean} @readOnly */ isEmpty: retrieveFromCurrentState, /** If this property is `true` the record is in the `loading` state. A record enters this state when the store asks the adapter for its data. It remains in this state until the adapter provides the requested data. @property isLoading @type {Boolean} @readOnly */ isLoading: retrieveFromCurrentState, /** If this property is `true` the record is in the `loaded` state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the `loaded` state. Example ```javascript var record = store.createRecord('model'); record.get('isLoaded'); // true store.find('model', 1).then(function(model) { model.get('isLoaded'); // true }); ``` @property isLoaded @type {Boolean} @readOnly */ isLoaded: retrieveFromCurrentState, /** If this property is `true` the record is in the `dirty` state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted. Example ```javascript var record = store.createRecord('model'); record.get('isDirty'); // true store.find('model', 1).then(function(model) { model.get('isDirty'); // false model.set('foo', 'some value'); model.get('isDirty'); // true }); ``` @property isDirty @type {Boolean} @readOnly */ isDirty: retrieveFromCurrentState, /** If this property is `true` the record is in the `saving` state. A record enters the saving state when `save` is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend. Example ```javascript var record = store.createRecord('model'); record.get('isSaving'); // false var promise = record.save(); record.get('isSaving'); // true promise.then(function() { record.get('isSaving'); // false }); ``` @property isSaving @type {Boolean} @readOnly */ isSaving: retrieveFromCurrentState, /** If this property is `true` the record is in the `deleted` state and has been marked for deletion. When `isDeleted` is true and `isDirty` is true, the record is deleted locally but the deletion was not yet persisted. When `isSaving` is true, the change is in-flight. When both `isDirty` and `isSaving` are false, the change has persisted. Example ```javascript var record = store.createRecord('model'); record.get('isDeleted'); // false record.deleteRecord(); // Locally deleted record.get('isDeleted'); // true record.get('isDirty'); // true record.get('isSaving'); // false // Persisting the deletion var promise = record.save(); record.get('isDeleted'); // true record.get('isSaving'); // true // Deletion Persisted promise.then(function() { record.get('isDeleted'); // true record.get('isSaving'); // false record.get('isDirty'); // false }); ``` @property isDeleted @type {Boolean} @readOnly */ isDeleted: retrieveFromCurrentState, /** If this property is `true` the record is in the `new` state. A record will be in the `new` state when it has been created on the client and the adapter has not yet report that it was successfully saved. Example ```javascript var record = store.createRecord('model'); record.get('isNew'); // true record.save().then(function(model) { model.get('isNew'); // false }); ``` @property isNew @type {Boolean} @readOnly */ isNew: retrieveFromCurrentState, /** If this property is `true` the record is in the `valid` state. A record will be in the `valid` state when the adapter did not report any server-side validation failures. @property isValid @type {Boolean} @readOnly */ isValid: retrieveFromCurrentState, /** If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are: - `created` The record has been created by the client and not yet saved to the adapter. - `updated` The record has been updated by the client and not yet saved to the adapter. - `deleted` The record has been deleted by the client and not yet saved to the adapter. Example ```javascript var record = store.createRecord('model'); record.get('dirtyType'); // 'created' ``` @property dirtyType @type {String} @readOnly */ dirtyType: retrieveFromCurrentState, /** If `true` the adapter reported that it was unable to save local changes to the backend for any reason other than a server-side validation error. Example ```javascript record.get('isError'); // false record.set('foo', 'valid value'); record.save().then(null, function() { record.get('isError'); // true }); ``` @property isError @type {Boolean} @readOnly */ isError: false, /** If `true` the store is attempting to reload the record form the adapter. Example ```javascript record.get('isReloading'); // false record.reload(); record.get('isReloading'); // true ``` @property isReloading @type {Boolean} @readOnly */ isReloading: false, /** The `clientId` property is a transient numerical identifier generated at runtime by the data store. It is important primarily because newly created objects may not yet have an externally generated id. @property clientId @private @type {Number|String} */ clientId: null, /** All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute. ```javascript var record = store.createRecord('model'); record.get('id'); // null store.find('model', 1).then(function(model) { model.get('id'); // '1' }); ``` @property id @type {String} */ id: null, /** @property currentState @private @type {Object} */ currentState: RootState.empty, /** When the record is in the `invalid` state this object will contain any errors returned by the adapter. When present the errors hash typically contains keys corresponding to the invalid property names and values which are an array of error messages. ```javascript record.get('errors.length'); // 0 record.set('foo', 'invalid value'); record.save().then(null, function() { record.get('errors').get('foo'); // ['foo should be a number.'] }); ``` @property errors @type {DS.Errors} */ errors: Ember.computed(function() { var errors = Errors.create(); errors.registerHandlers(this, function() { this.send('becameInvalid'); }, function() { this.send('becameValid'); }); return errors; }).readOnly(), /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. `serialize` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method serialize @param {Object} options @return {Object} an object whose values are primitive JSON values only */ serialize: function(options) { var store = get(this, 'store'); return store.serialize(this, options); }, /** Use [DS.JSONSerializer](DS.JSONSerializer.html) to get the JSON representation of a record. `toJSON` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method toJSON @param {Object} options @return {Object} A JSON representation of the object. */ toJSON: function(options) { if (!JSONSerializer) { JSONSerializer = requireModule("ember-data/lib/serializers/json_serializer")["default"]; } // container is for lazy transform lookups var serializer = JSONSerializer.create({ container: this.container }); return serializer.serialize(this, options); }, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: Ember.K, /** Fired when the record is updated. @event didUpdate */ didUpdate: Ember.K, /** Fired when the record is created. @event didCreate */ didCreate: Ember.K, /** Fired when the record is deleted. @event didDelete */ didDelete: Ember.K, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: Ember.K, /** Fired when the record enters the error state. @event becameError */ becameError: Ember.K, /** @property data @private @type {Object} */ data: Ember.computed(function() { this._data = this._data || {}; return this._data; }).readOnly(), _data: null, init: function() { this._super(); this._setup(); }, _setup: function() { this._changesToSync = {}; this._deferredTriggers = []; this._data = {}; this._attributes = {}; this._inFlightAttributes = {}; this._relationships = {}; }, /** @method send @private @param {String} name @param {Object} context */ send: function(name, context) { var currentState = get(this, 'currentState'); if (!currentState[name]) { this._unhandledEvent(currentState, name, context); } return currentState[name](this, context); }, /** @method transitionTo @private @param {String} name */ transitionTo: function(name) { // POSSIBLE TODO: Remove this code and replace with // always having direct references to state objects var pivotName = name.split(".", 1), currentState = get(this, 'currentState'), state = currentState; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state.hasOwnProperty(pivotName)); var path = name.split("."); var setups = [], enters = [], i, l; for (i=0, l=path.length; i<l; i++) { state = state[path[i]]; if (state.enter) { enters.push(state); } if (state.setup) { setups.push(state); } } for (i=0, l=enters.length; i<l; i++) { enters[i].enter(this); } set(this, 'currentState', state); for (i=0, l=setups.length; i<l; i++) { setups[i].setup(this); } this.updateRecordArraysLater(); }, _unhandledEvent: function(state, name, context) { var errorMessage = "Attempted to handle event `" + name + "` "; errorMessage += "on " + String(this) + " while in state "; errorMessage += state.stateName + ". "; if (context !== undefined) { errorMessage += "Called with " + Ember.inspect(context) + "."; } throw new Ember.Error(errorMessage); }, withTransaction: function(fn) { var transaction = get(this, 'transaction'); if (transaction) { fn(transaction); } }, /** @method loadingData @private @param {Promise} promise */ loadingData: function(promise) { this.send('loadingData', promise); }, /** @method loadedData @private */ loadedData: function() { this.send('loadedData'); }, /** @method notFound @private */ notFound: function() { this.send('notFound'); }, /** @method pushedData @private */ pushedData: function() { this.send('pushedData'); }, /** Marks the record as deleted but does not save it. You must call `save` afterwards if you want to persist it. You might use this method if you want to allow the user to still `rollback()` a delete after it was made. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { softDelete: function() { this.get('model').deleteRecord(); }, confirm: function() { this.get('model').save(); }, undo: function() { this.get('model').rollback(); } } }); ``` @method deleteRecord */ deleteRecord: function() { this.send('deleteRecord'); }, /** Same as `deleteRecord`, but saves the record immediately. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { delete: function() { var controller = this.controller; this.get('model').destroyRecord().then(function() { controller.transitionToRoute('model.index'); }); } } }); ``` @method destroyRecord @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ destroyRecord: function() { this.deleteRecord(); return this.save(); }, /** @method unloadRecord @private */ unloadRecord: function() { if (this.isDestroyed) { return; } this.send('unloadRecord'); }, /** @method clearRelationships @private */ clearRelationships: function() { this.eachRelationship(function(name, relationship) { if (relationship.kind === 'belongsTo') { set(this, name, null); } else if (relationship.kind === 'hasMany') { var hasMany = this._relationships[name]; if (hasMany) { // relationships are created lazily hasMany.destroy(); } } }, this); }, /** @method updateRecordArrays @private */ updateRecordArrays: function() { this._updatingRecordArraysLater = false; get(this, 'store').dataWasUpdated(this.constructor, this); }, /** Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. Example ```javascript App.Mascot = DS.Model.extend({ name: attr('string') }); var person = store.createRecord('person'); person.changedAttributes(); // {} person.set('name', 'Tomster'); person.changedAttributes(); // {name: [undefined, 'Tomster']} ``` @method changedAttributes @return {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function() { var oldData = get(this, '_data'), newData = get(this, '_attributes'), diffData = {}, prop; for (prop in newData) { diffData[prop] = [oldData[prop], newData[prop]]; } return diffData; }, /** @method adapterWillCommit @private */ adapterWillCommit: function() { this.send('willCommit'); }, /** If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. @method adapterDidCommit */ adapterDidCommit: function(data) { set(this, 'isError', false); if (data) { this._data = data; } else { Ember.mixin(this._data, this._inFlightAttributes); } this._inFlightAttributes = {}; this.send('didCommit'); this.updateRecordArraysLater(); if (!data) { return; } this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, /** @method adapterDidDirty @private */ adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, dataDidChange: Ember.observer(function() { this.reloadHasManys(); }, 'data'), reloadHasManys: function() { var relationships = get(this.constructor, 'relationshipsByName'); this.updateRecordArraysLater(); relationships.forEach(function(name, relationship) { if (this._data.links && this._data.links[name]) { return; } if (relationship.kind === 'hasMany') { this.hasManyDidChange(relationship.key); } }, this); }, hasManyDidChange: function(key) { var hasMany = this._relationships[key]; if (hasMany) { var records = this._data[key] || []; set(hasMany, 'content', Ember.A(records)); set(hasMany, 'isLoaded', true); hasMany.trigger('didLoad'); } }, /** @method updateRecordArraysLater @private */ updateRecordArraysLater: function() { // quick hack (something like this could be pushed into run.once if (this._updatingRecordArraysLater) { return; } this._updatingRecordArraysLater = true; Ember.run.schedule('actions', this, this.updateRecordArrays); }, /** @method setupData @private @param {Object} data @param {Boolean} partial the data should be merged into the existing data, not replace it. */ setupData: function(data, partial) { if (partial) { Ember.merge(this._data, data); } else { this._data = data; } var relationships = this._relationships; this.eachRelationship(function(name, rel) { if (data.links && data.links[name]) { return; } if (rel.options.async) { relationships[name] = null; } }); if (data) { this.pushedData(); } this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, materializeId: function(id) { set(this, 'id', id); }, materializeAttributes: function(attributes) { merge(this._data, attributes); }, materializeAttribute: function(name, value) { this._data[name] = value; }, /** @method updateHasMany @private @param {String} name @param {Array} records */ updateHasMany: function(name, records) { this._data[name] = records; this.hasManyDidChange(name); }, /** @method updateBelongsTo @private @param {String} name @param {DS.Model} record */ updateBelongsTo: function(name, record) { this._data[name] = record; }, /** If the model `isDirty` this function will discard any unsaved changes Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollback(); record.get('name'); // 'Untitled Document' ``` @method rollback */ rollback: function() { this._attributes = {}; if (get(this, 'isError')) { this._inFlightAttributes = {}; set(this, 'isError', false); } if (!get(this, 'isValid')) { this._inFlightAttributes = {}; } this.send('rolledBack'); this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, toStringExtension: function() { return get(this, 'id'); }, /** The goal of this method is to temporarily disable specific observers that take action in response to application changes. This allows the system to make changes (such as materialization and rollback) that should not trigger secondary behavior (such as setting an inverse relationship or marking records as dirty). The specific implementation will likely change as Ember proper provides better infrastructure for suspending groups of observers, and if Array observation becomes more unified with regular observers. @method suspendRelationshipObservers @private @param callback @param binding */ suspendRelationshipObservers: function(callback, binding) { var observers = get(this.constructor, 'relationshipNames').belongsTo; var self = this; try { this._suspendedRelationships = true; Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() { Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() { callback.call(binding || self); }); }); } finally { this._suspendedRelationships = false; } }, /** Save the record and persist any changes to the record to an extenal source via the adapter. Example ```javascript record.set('name', 'Tomster'); record.save().then(function(){ // Success callback }, function() { // Error callback }); ``` @method save @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ save: function() { var promiseLabel = "DS: Model#save " + this; var resolver = Ember.RSVP.defer(promiseLabel); this.get('store').scheduleSave(this, resolver); this._inFlightAttributes = this._attributes; this._attributes = {}; return PromiseObject.create({ promise: resolver.promise }); }, /** Reload the record from the adapter. This will only work if the record has already finished loading and has not yet been modified (`isLoaded` but not `isDirty`, or `isSaving`). Example ```javascript App.ModelViewRoute = Ember.Route.extend({ actions: { reload: function() { this.get('model').reload(); } } }); ``` @method reload @return {Promise} a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error. */ reload: function() { set(this, 'isReloading', true); var record = this; var promiseLabel = "DS: Model#reload of " + this; var promise = new Promise(function(resolve){ record.send('reloadRecord', resolve); }, promiseLabel).then(function() { record.set('isReloading', false); record.set('isError', false); return record; }, function(reason) { record.set('isError', true); throw reason; }, "DS: Model#reload complete, update flags"); return PromiseObject.create({ promise: promise }); }, // FOR USE DURING COMMIT PROCESS adapterDidUpdateAttribute: function(attributeName, value) { // If a value is passed in, update the internal attributes and clear // the attribute cache so it picks up the new value. Otherwise, // collapse the current value into the internal attributes because // the adapter has acknowledged it. if (value !== undefined) { this._data[attributeName] = value; this.notifyPropertyChange(attributeName); } else { this._data[attributeName] = this._inFlightAttributes[attributeName]; } this.updateRecordArraysLater(); }, /** @method adapterDidInvalidate @private */ adapterDidInvalidate: function(errors) { var recordErrors = get(this, 'errors'); function addError(name) { if (errors[name]) { recordErrors.add(name, errors[name]); } } this.eachAttribute(addError); this.eachRelationship(addError); }, /** @method adapterDidError @private */ adapterDidError: function() { this.send('becameError'); set(this, 'isError', true); }, /** Override the default event firing from Ember.Evented to also call methods with the given name. @method trigger @private @param name */ trigger: function(name) { Ember.tryInvoke(this, name, [].slice.call(arguments, 1)); this._super.apply(this, arguments); }, triggerLater: function() { if (this._deferredTriggers.push(arguments) !== 1) { return; } Ember.run.schedule('actions', this, '_triggerDeferredTriggers'); }, _triggerDeferredTriggers: function() { for (var i=0, l=this._deferredTriggers.length; i<l; i++) { this.trigger.apply(this, this._deferredTriggers[i]); } this._deferredTriggers.length = 0; }, willDestroy: function() { this._super(); this.clearRelationships(); } }); Model.reopenClass({ /** Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model instances from within the store, but if end users accidentally call `create()` (instead of `createRecord()`), we can raise an error. @method _create @private @static */ _create: Model.create, /** Override the class' `create()` method to raise an error. This prevents end users from inadvertently calling `create()` instead of `createRecord()`. The store is still able to create instances by calling the `_create()` method. To create an instance of a `DS.Model` use [store.createRecord](DS.Store.html#method_createRecord). @method create @private @static */ create: function() { throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); } }); __exports__["default"] = Model; }); define("ember-data/lib/system/model/states", ["exports"], function(__exports__) { "use strict"; /** @module ember-data */ var get = Ember.get, set = Ember.set; /* This file encapsulates the various states that a record can transition through during its lifecycle. */ /** ### State Each record has a `currentState` property that explicitly tracks what state a record is in at any given time. For instance, if a record is newly created and has not yet been sent to the adapter to be saved, it would be in the `root.loaded.created.uncommitted` state. If a record has had local modifications made to it that are in the process of being saved, the record would be in the `root.loaded.updated.inFlight` state. (These state paths will be explained in more detail below.) Events are sent by the record or its store to the record's `currentState` property. How the state reacts to these events is dependent on which state it is in. In some states, certain events will be invalid and will cause an exception to be raised. States are hierarchical and every state is a substate of the `RootState`. For example, a record can be in the `root.deleted.uncommitted` state, then transition into the `root.deleted.inFlight` state. If a child state does not implement an event handler, the state manager will attempt to invoke the event on all parent states until the root state is reached. The state hierarchy of a record is described in terms of a path string. You can determine a record's current state by getting the state's `stateName` property: ```javascript record.get('currentState.stateName'); //=> "root.created.uncommitted" ``` The hierarchy of valid states that ship with ember data looks like this: ```text * root * deleted * saved * uncommitted * inFlight * empty * loaded * created * uncommitted * inFlight * saved * updated * uncommitted * inFlight * loading ``` The `DS.Model` states are themselves stateless. What we mean is that, the hierarchical states that each of *those* points to is a shared data structure. For performance reasons, instead of each record getting its own copy of the hierarchy of states, each record points to this global, immutable shared instance. How does a state know which record it should be acting on? We pass the record instance into the state's event handlers as the first argument. The record passed as the first parameter is where you should stash state about the record if needed; you should never store data on the state object itself. ### Events and Flags A state may implement zero or more events and flags. #### Events Events are named functions that are invoked when sent to a record. The record will first look for a method with the given name on the current state. If no method is found, it will search the current state's parent, and then its grandparent, and so on until reaching the top of the hierarchy. If the root is reached without an event handler being found, an exception will be raised. This can be very helpful when debugging new features. Here's an example implementation of a state with a `myEvent` event handler: ```javascript aState: DS.State.create({ myEvent: function(manager, param) { console.log("Received myEvent with", param); } }) ``` To trigger this event: ```javascript record.send('myEvent', 'foo'); //=> "Received myEvent with foo" ``` Note that an optional parameter can be sent to a record's `send()` method, which will be passed as the second parameter to the event handler. Events should transition to a different state if appropriate. This can be done by calling the record's `transitionTo()` method with a path to the desired state. The state manager will attempt to resolve the state path relative to the current state. If no state is found at that path, it will attempt to resolve it relative to the current state's parent, and then its parent, and so on until the root is reached. For example, imagine a hierarchy like this: * created * uncommitted <-- currentState * inFlight * updated * inFlight If we are currently in the `uncommitted` state, calling `transitionTo('inFlight')` would transition to the `created.inFlight` state, while calling `transitionTo('updated.inFlight')` would transition to the `updated.inFlight` state. Remember that *only events* should ever cause a state transition. You should never call `transitionTo()` from outside a state's event handler. If you are tempted to do so, create a new event and send that to the state manager. #### Flags Flags are Boolean values that can be used to introspect a record's current state in a more user-friendly way than examining its state path. For example, instead of doing this: ```javascript var statePath = record.get('stateManager.currentPath'); if (statePath === 'created.inFlight') { doSomething(); } ``` You can say: ```javascript if (record.get('isNew') && record.get('isSaving')) { doSomething(); } ``` If your state does not set a value for a given flag, the value will be inherited from its parent (or the first place in the state hierarchy where it is defined). The current set of flags are defined below. If you want to add a new flag, in addition to the area below, you will also need to declare it in the `DS.Model` class. * [isEmpty](DS.Model.html#property_isEmpty) * [isLoading](DS.Model.html#property_isLoading) * [isLoaded](DS.Model.html#property_isLoaded) * [isDirty](DS.Model.html#property_isDirty) * [isSaving](DS.Model.html#property_isSaving) * [isDeleted](DS.Model.html#property_isDeleted) * [isNew](DS.Model.html#property_isNew) * [isValid](DS.Model.html#property_isValid) @namespace DS @class RootState */ function hasDefinedProperties(object) { // Ignore internal property defined by simulated `Ember.create`. var names = Ember.keys(object); var i, l, name; for (i = 0, l = names.length; i < l; i++ ) { name = names[i]; if (object.hasOwnProperty(name) && object[name]) { return true; } } return false; } function didSetProperty(record, context) { if (context.value === context.originalValue) { delete record._attributes[context.name]; record.send('propertyWasReset', context.name); } else if (context.value !== context.oldValue) { record.send('becomeDirty'); } record.updateRecordArraysLater(); } // Implementation notes: // // Each state has a boolean value for all of the following flags: // // * isLoaded: The record has a populated `data` property. When a // record is loaded via `store.find`, `isLoaded` is false // until the adapter sets it. When a record is created locally, // its `isLoaded` property is always true. // * isDirty: The record has local changes that have not yet been // saved by the adapter. This includes records that have been // created (but not yet saved) or deleted. // * isSaving: The record has been committed, but // the adapter has not yet acknowledged that the changes have // been persisted to the backend. // * isDeleted: The record was marked for deletion. When `isDeleted` // is true and `isDirty` is true, the record is deleted locally // but the deletion was not yet persisted. When `isSaving` is // true, the change is in-flight. When both `isDirty` and // `isSaving` are false, the change has persisted. // * isError: The adapter reported that it was unable to save // local changes to the backend. This may also result in the // record having its `isValid` property become false if the // adapter reported that server-side validations failed. // * isNew: The record was created on the client and the adapter // did not yet report that it was successfully saved. // * isValid: The adapter did not report any server-side validation // failures. // The dirty state is a abstract state whose functionality is // shared between the `created` and `updated` states. // // The deleted state shares the `isDirty` flag with the // subclasses of `DirtyState`, but with a very different // implementation. // // Dirty states have three child states: // // `uncommitted`: the store has not yet handed off the record // to be saved. // `inFlight`: the store has handed off the record to be saved, // but the adapter has not yet acknowledged success. // `invalid`: the record has invalid information and cannot be // send to the adapter yet. var DirtyState = { initialState: 'uncommitted', // FLAGS isDirty: true, // SUBSTATES // When a record first becomes dirty, it is `uncommitted`. // This means that there are local pending changes, but they // have not yet begun to be saved, and are not invalid. uncommitted: { // EVENTS didSetProperty: didSetProperty, propertyWasReset: function(record, name) { var stillDirty = false; for (var prop in record._attributes) { stillDirty = true; break; } if (!stillDirty) { record.send('rolledBack'); } }, pushedData: Ember.K, becomeDirty: Ember.K, willCommit: function(record) { record.transitionTo('inFlight'); }, reloadRecord: function(record, resolve) { resolve(get(record, 'store').reloadRecord(record)); }, rolledBack: function(record) { record.transitionTo('loaded.saved'); }, becameInvalid: function(record) { record.transitionTo('invalid'); }, rollback: function(record) { record.rollback(); } }, // Once a record has been handed off to the adapter to be // saved, it is in the 'in flight' state. Changes to the // record cannot be made during this window. inFlight: { // FLAGS isSaving: true, // EVENTS didSetProperty: didSetProperty, becomeDirty: Ember.K, pushedData: Ember.K, unloadRecord: function(record) { }, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { var dirtyType = get(this, 'dirtyType'); record.transitionTo('saved'); record.send('invokeLifecycleCallbacks', dirtyType); }, becameInvalid: function(record) { record.transitionTo('invalid'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // A record is in the `invalid` if the adapter has indicated // the the record failed server-side invalidations. invalid: { // FLAGS isValid: false, // EVENTS deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }, didSetProperty: function(record, context) { get(record, 'errors').remove(context.name); didSetProperty(record, context); }, becomeDirty: Ember.K, willCommit: function(record) { get(record, 'errors').clear(); record.transitionTo('inFlight'); }, rolledBack: function(record) { get(record, 'errors').clear(); }, becameValid: function(record) { record.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('becameInvalid', record); }, exit: function(record) { record._inFlightAttributes = {}; } } }; // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. function deepClone(object) { var clone = {}, value; for (var prop in object) { value = object[prop]; if (value && typeof value === 'object') { clone[prop] = deepClone(value); } else { clone[prop] = value; } } return clone; } function mixin(original, hash) { for (var prop in hash) { original[prop] = hash[prop]; } return original; } function dirtyState(options) { var newState = deepClone(DirtyState); return mixin(newState, options); } var createdState = dirtyState({ dirtyType: 'created', // FLAGS isNew: true }); createdState.uncommitted.rolledBack = function(record) { record.transitionTo('deleted.saved'); }; var updatedState = dirtyState({ dirtyType: 'updated' }); createdState.uncommitted.deleteRecord = function(record) { record.clearRelationships(); record.transitionTo('deleted.saved'); }; createdState.uncommitted.rollback = function(record) { DirtyState.uncommitted.rollback.apply(this, arguments); record.transitionTo('deleted.saved'); }; createdState.uncommitted.propertyWasReset = Ember.K; function assertAgainstUnloadRecord(record) { } updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord; updatedState.uncommitted.deleteRecord = function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }; var RootState = { // FLAGS isEmpty: false, isLoading: false, isLoaded: false, isDirty: false, isSaving: false, isDeleted: false, isNew: false, isValid: true, // DEFAULT EVENTS // Trying to roll back if you're not in the dirty state // doesn't change your state. For example, if you're in the // in-flight state, rolling back the record doesn't move // you out of the in-flight state. rolledBack: Ember.K, unloadRecord: function(record) { // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); record.transitionTo('deleted.saved'); }, propertyWasReset: Ember.K, // SUBSTATES // A record begins its lifecycle in the `empty` state. // If its data will come from the adapter, it will // transition into the `loading` state. Otherwise, if // the record is being created on the client, it will // transition into the `created` state. empty: { isEmpty: true, // EVENTS loadingData: function(record, promise) { record._loadingPromise = promise; record.transitionTo('loading'); }, loadedData: function(record) { record.transitionTo('loaded.created.uncommitted'); record.suspendRelationshipObservers(function() { record.notifyPropertyChange('data'); }); }, pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); } }, // A record enters this state when the store asks // the adapter for its data. It remains in this state // until the adapter provides the requested data. // // Usually, this process is asynchronous, using an // XHR to retrieve the data. loading: { // FLAGS isLoading: true, exit: function(record) { record._loadingPromise = null; }, // EVENTS pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); set(record, 'isError', false); }, becameError: function(record) { record.triggerLater('becameError', record); }, notFound: function(record) { record.transitionTo('empty'); } }, // A record enters this state when its data is populated. // Most of a record's lifecycle is spent inside substates // of the `loaded` state. loaded: { initialState: 'saved', // FLAGS isLoaded: true, // SUBSTATES // If there are no local changes to a record, it remains // in the `saved` state. saved: { setup: function(record) { var attrs = record._attributes, isDirty = false; for (var prop in attrs) { if (attrs.hasOwnProperty(prop)) { isDirty = true; break; } } if (isDirty) { record.adapterDidDirty(); } }, // EVENTS didSetProperty: didSetProperty, pushedData: Ember.K, becomeDirty: function(record) { record.transitionTo('updated.uncommitted'); }, willCommit: function(record) { record.transitionTo('updated.inFlight'); }, reloadRecord: function(record, resolve) { resolve(get(record, 'store').reloadRecord(record)); }, deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }, unloadRecord: function(record) { // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); record.transitionTo('deleted.saved'); }, didCommit: function(record) { record.send('invokeLifecycleCallbacks', get(record, 'lastDirtyType')); }, // loaded.saved.notFound would be triggered by a failed // `reload()` on an unchanged record notFound: Ember.K }, // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: createdState, // A record is in this state if it has already been // saved to the server, but there are new local changes // that have not yet been saved. updated: updatedState }, // A record is in this state if it was deleted from the store. deleted: { initialState: 'uncommitted', dirtyType: 'deleted', // FLAGS isDeleted: true, isLoaded: true, isDirty: true, // TRANSITIONS setup: function(record) { record.updateRecordArrays(); }, // SUBSTATES // When a record is deleted, it enters the `start` // state. It will exit this state when the record // starts to commit. uncommitted: { // EVENTS willCommit: function(record) { record.transitionTo('inFlight'); }, rollback: function(record) { record.rollback(); }, becomeDirty: Ember.K, deleteRecord: Ember.K, rolledBack: function(record) { record.transitionTo('loaded.saved'); } }, // After a record starts committing, but // before the adapter indicates that the deletion // has saved to the server, a record is in the // `inFlight` substate of `deleted`. inFlight: { // FLAGS isSaving: true, // EVENTS unloadRecord: assertAgainstUnloadRecord, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { record.transitionTo('saved'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: { // FLAGS isDirty: false, setup: function(record) { var store = get(record, 'store'); store.dematerializeRecord(record); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('didDelete', record); record.triggerLater('didCommit', record); }, willCommit: Ember.K, didCommit: Ember.K } }, invokeLifecycleCallbacks: function(record, dirtyType) { if (dirtyType === 'created') { record.triggerLater('didCreate', record); } else { record.triggerLater('didUpdate', record); } record.triggerLater('didCommit', record); } }; function wireState(object, parent, name) { /*jshint proto:true*/ // TODO: Use Object.create and copy instead object = mixin(parent ? Ember.create(parent) : {}, object); object.parentState = parent; object.stateName = name; for (var prop in object) { if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; } if (typeof object[prop] === 'object') { object[prop] = wireState(object[prop], object, name + "." + prop); } } return object; } RootState = wireState(RootState, null, "root"); __exports__["default"] = RootState; }); define("ember-data/lib/system/record_array_manager", ["./record_arrays","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var RecordArray = __dependency1__.RecordArray; var FilteredRecordArray = __dependency1__.FilteredRecordArray; var AdapterPopulatedRecordArray = __dependency1__.AdapterPopulatedRecordArray; var ManyArray = __dependency1__.ManyArray; var get = Ember.get, set = Ember.set; var forEach = Ember.EnumerableUtils.forEach; /** @class RecordArrayManager @namespace DS @private @extends Ember.Object */ var RecordArrayManager = Ember.Object.extend({ init: function() { this.filteredRecordArrays = Ember.MapWithDefault.create({ defaultValue: function() { return []; } }); this.changedRecords = []; this._adapterPopulatedRecordArrays = []; }, recordDidChange: function(record) { if (this.changedRecords.push(record) !== 1) { return; } Ember.run.schedule('actions', this, this.updateRecordArrays); }, recordArraysForRecord: function(record) { record._recordArrays = record._recordArrays || Ember.OrderedSet.create(); return record._recordArrays; }, /** This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter, or when a record has changed. It updates all record arrays that a record belongs to. To avoid thrashing, it only runs at most once per run loop. @method updateRecordArrays @param {Class} type @param {Number|String} clientId */ updateRecordArrays: function() { forEach(this.changedRecords, function(record) { if (get(record, 'isDeleted')) { this._recordWasDeleted(record); } else { this._recordWasChanged(record); } }, this); this.changedRecords.length = 0; }, _recordWasDeleted: function (record) { var recordArrays = record._recordArrays; if (!recordArrays) { return; } forEach(recordArrays, function(array) { array.removeRecord(record); }); }, _recordWasChanged: function (record) { var type = record.constructor, recordArrays = this.filteredRecordArrays.get(type), filter; forEach(recordArrays, function(array) { filter = get(array, 'filterFunction'); this.updateRecordArray(array, filter, type, record); }, this); // loop through all manyArrays containing an unloaded copy of this // clientId and notify them that the record was loaded. var manyArrays = record._loadingRecordArrays; if (manyArrays) { for (var i=0, l=manyArrays.length; i<l; i++) { manyArrays[i].loadedRecord(); } record._loadingRecordArrays = []; } }, /** Update an individual filter. @method updateRecordArray @param {DS.FilteredRecordArray} array @param {Function} filter @param {Class} type @param {Number|String} clientId */ updateRecordArray: function(array, filter, type, record) { var shouldBeInArray; if (!filter) { shouldBeInArray = true; } else { shouldBeInArray = filter(record); } var recordArrays = this.recordArraysForRecord(record); if (shouldBeInArray) { recordArrays.add(array); array.addRecord(record); } else if (!shouldBeInArray) { recordArrays.remove(array); array.removeRecord(record); } }, /** This method is invoked if the `filterFunction` property is changed on a `DS.FilteredRecordArray`. It essentially re-runs the filter from scratch. This same method is invoked when the filter is created in th first place. @method updateFilter @param array @param type @param filter */ updateFilter: function(array, type, filter) { var typeMap = this.store.typeMapFor(type), records = typeMap.records, record; for (var i=0, l=records.length; i<l; i++) { record = records[i]; if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) { this.updateRecordArray(array, filter, type, record); } } }, /** Create a `DS.ManyArray` for a type and list of record references, and index the `ManyArray` under each reference. This allows us to efficiently remove records from `ManyArray`s when they are deleted. @method createManyArray @param {Class} type @param {Array} references @return {DS.ManyArray} */ createManyArray: function(type, records) { var manyArray = ManyArray.create({ type: type, content: records, store: this.store }); forEach(records, function(record) { var arrays = this.recordArraysForRecord(record); arrays.add(manyArray); }, this); return manyArray; }, /** Create a `DS.RecordArray` for a type and register it for updates. @method createRecordArray @param {Class} type @return {DS.RecordArray} */ createRecordArray: function(type) { var array = RecordArray.create({ type: type, content: Ember.A(), store: this.store, isLoaded: true }); this.registerFilteredRecordArray(array, type); return array; }, /** Create a `DS.FilteredRecordArray` for a type and register it for updates. @method createFilteredRecordArray @param {Class} type @param {Function} filter @param {Object} query (optional @return {DS.FilteredRecordArray} */ createFilteredRecordArray: function(type, filter, query) { var array = FilteredRecordArray.create({ query: query, type: type, content: Ember.A(), store: this.store, manager: this, filterFunction: filter }); this.registerFilteredRecordArray(array, type, filter); return array; }, /** Create a `DS.AdapterPopulatedRecordArray` for a type with given query. @method createAdapterPopulatedRecordArray @param {Class} type @param {Object} query @return {DS.AdapterPopulatedRecordArray} */ createAdapterPopulatedRecordArray: function(type, query) { var array = AdapterPopulatedRecordArray.create({ type: type, query: query, content: Ember.A(), store: this.store, manager: this }); this._adapterPopulatedRecordArrays.push(array); return array; }, /** Register a RecordArray for a given type to be backed by a filter function. This will cause the array to update automatically when records of that type change attribute values or states. @method registerFilteredRecordArray @param {DS.RecordArray} array @param {Class} type @param {Function} filter */ registerFilteredRecordArray: function(array, type, filter) { var recordArrays = this.filteredRecordArrays.get(type); recordArrays.push(array); this.updateFilter(array, type, filter); }, // Internally, we maintain a map of all unloaded IDs requested by // a ManyArray. As the adapter loads data into the store, the // store notifies any interested ManyArrays. When the ManyArray's // total number of loading records drops to zero, it becomes // `isLoaded` and fires a `didLoad` event. registerWaitingRecordArray: function(record, array) { var loadingRecordArrays = record._loadingRecordArrays || []; loadingRecordArrays.push(array); record._loadingRecordArrays = loadingRecordArrays; }, willDestroy: function(){ this._super(); forEach(flatten(values(this.filteredRecordArrays.values)), destroy); forEach(this._adapterPopulatedRecordArrays, destroy); } }); function values(obj) { var result = []; var keys = Ember.keys(obj); for (var i = 0; i < keys.length; i++) { result.push(obj[keys[i]]); } return result; } function destroy(entry) { entry.destroy(); } function flatten(list) { var length = list.length; var result = Ember.A(); for (var i = 0; i < length; i++) { result = result.concat(list[i]); } return result; } __exports__["default"] = RecordArrayManager; }); define("ember-data/lib/system/record_arrays", ["./record_arrays/record_array","./record_arrays/filtered_record_array","./record_arrays/adapter_populated_record_array","./record_arrays/many_array","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; /** @module ember-data */ var RecordArray = __dependency1__["default"]; var FilteredRecordArray = __dependency2__["default"]; var AdapterPopulatedRecordArray = __dependency3__["default"]; var ManyArray = __dependency4__["default"]; __exports__.RecordArray = RecordArray; __exports__.FilteredRecordArray = FilteredRecordArray; __exports__.AdapterPopulatedRecordArray = AdapterPopulatedRecordArray; __exports__.ManyArray = ManyArray; }); define("ember-data/lib/system/record_arrays/adapter_populated_record_array", ["./record_array","exports"], function(__dependency1__, __exports__) { "use strict"; var RecordArray = __dependency1__["default"]; /** @module ember-data */ var get = Ember.get, set = Ember.set; /** Represents an ordered list of records whose order and membership is determined by the adapter. For example, a query sent to the adapter may trigger a search on the server, whose results would be loaded into an instance of the `AdapterPopulatedRecordArray`. @class AdapterPopulatedRecordArray @namespace DS @extends DS.RecordArray */ var AdapterPopulatedRecordArray = RecordArray.extend({ query: null, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, /** @method load @private @param {Array} data */ load: function(data) { var store = get(this, 'store'), type = get(this, 'type'), records = store.pushMany(type, data), meta = store.metadataFor(type); this.setProperties({ content: Ember.A(records), isLoaded: true, meta: Ember.copy(meta) }); records.forEach(function(record) { this.manager.recordArraysForRecord(record).add(this); }, this); // TODO: should triggering didLoad event be the last action of the runLoop? Ember.run.once(this, 'trigger', 'didLoad'); } }); __exports__["default"] = AdapterPopulatedRecordArray; }); define("ember-data/lib/system/record_arrays/filtered_record_array", ["./record_array","exports"], function(__dependency1__, __exports__) { "use strict"; var RecordArray = __dependency1__["default"]; /** @module ember-data */ var get = Ember.get; /** Represents a list of records whose membership is determined by the store. As records are created, loaded, or modified, the store evaluates them to determine if they should be part of the record array. @class FilteredRecordArray @namespace DS @extends DS.RecordArray */ var FilteredRecordArray = RecordArray.extend({ /** The filterFunction is a function used to test records from the store to determine if they should be part of the record array. Example ```javascript var allPeople = store.all('person'); allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"] var people = store.filter('person', function(person) { if (person.get('name').match(/Katz$/)) { return true; } }); people.mapBy('name'); // ["Yehuda Katz"] var notKatzFilter = function(person) { return !person.get('name').match(/Katz$/); }; people.set('filterFunction', notKatzFilter); people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"] ``` @method filterFunction @param {DS.Model} record @return {Boolean} `true` if the record should be in the array */ filterFunction: null, isLoaded: true, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a client-side filter (on " + type + ") is immutable."); }, /** @method updateFilter @private */ _updateFilter: function() { var manager = get(this, 'manager'); manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction')); }, updateFilter: Ember.observer(function() { Ember.run.once(this, this._updateFilter); }, 'filterFunction') }); __exports__["default"] = FilteredRecordArray; }); define("ember-data/lib/system/record_arrays/many_array", ["./record_array","../changes","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var RecordArray = __dependency1__["default"]; var RelationshipChange = __dependency2__.RelationshipChange; /** @module ember-data */ var get = Ember.get, set = Ember.set; var map = Ember.EnumerableUtils.map; function sync(change) { change.sync(); } /** A `ManyArray` is a `RecordArray` that represents the contents of a has-many relationship. The `ManyArray` is instantiated lazily the first time the relationship is requested. ### Inverses Often, the relationships in Ember Data applications will have an inverse. For example, imagine the following models are defined: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` If you created a new instance of `App.Post` and added a `App.Comment` record to its `comments` has-many relationship, you would expect the comment's `post` property to be set to the post that contained the has-many. We call the record to which a relationship belongs the relationship's _owner_. @class ManyArray @namespace DS @extends DS.RecordArray */ var ManyArray = RecordArray.extend({ init: function() { this._super.apply(this, arguments); this._changesToSync = Ember.OrderedSet.create(); }, /** The property name of the relationship @property {String} name @private */ name: null, /** The record to which this relationship belongs. @property {DS.Model} owner @private */ owner: null, /** `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} isPolymorphic @private */ isPolymorphic: false, // LOADING STATE isLoaded: false, /** Used for async `hasMany` arrays to keep track of when they will resolve. @property {Ember.RSVP.Promise} promise @private */ promise: null, /** @method loadingRecordsCount @param {Number} count @private */ loadingRecordsCount: function(count) { this.loadingRecordsCount = count; }, /** @method loadedRecord @private */ loadedRecord: function() { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { set(this, 'isLoaded', true); this.trigger('didLoad'); } }, /** @method fetch @private */ fetch: function() { var records = get(this, 'content'), store = get(this, 'store'), owner = get(this, 'owner'); var unloadedRecords = records.filterProperty('isEmpty', true); store.fetchMany(unloadedRecords, owner); }, // Overrides Ember.Array's replace method to implement replaceContent: function(index, removed, added) { // Map the array of record objects into an array of client ids. added = map(added, function(record) { return record; }, this); this._super(index, removed, added); }, arrangedContentDidChange: function() { Ember.run.once(this, 'fetch'); }, arrayContentWillChange: function(index, removed, added) { var owner = get(this, 'owner'), name = get(this, 'name'); if (!owner._suspendedRelationships) { // This code is the first half of code that continues inside // of arrayContentDidChange. It gets or creates a change from // the child object, adds the current owner as the old // parent if this is the first time the object was removed // from a ManyArray, and sets `newParent` to null. // // Later, if the object is added to another ManyArray, // the `arrayContentDidChange` will set `newParent` on // the change. for (var i=index; i<index+removed; i++) { var record = get(this, 'content').objectAt(i); var change = RelationshipChange.createChange(owner, record, get(this, 'store'), { parentType: owner.constructor, changeType: "remove", kind: "hasMany", key: name }); this._changesToSync.add(change); } } return this._super.apply(this, arguments); }, arrayContentDidChange: function(index, removed, added) { this._super.apply(this, arguments); var owner = get(this, 'owner'), name = get(this, 'name'), store = get(this, 'store'); if (!owner._suspendedRelationships) { // This code is the second half of code that started in // `arrayContentWillChange`. It gets or creates a change // from the child object, and adds the current owner as // the new parent. for (var i=index; i<index+added; i++) { var record = get(this, 'content').objectAt(i); var change = RelationshipChange.createChange(owner, record, store, { parentType: owner.constructor, changeType: "add", kind:"hasMany", key: name }); change.hasManyName = name; this._changesToSync.add(change); } // We wait until the array has finished being // mutated before syncing the OneToManyChanges created // in arrayContentWillChange, so that the array // membership test in the sync() logic operates // on the final results. this._changesToSync.forEach(sync); this._changesToSync.clear(); } }, /** Create a child record within the owner @method createRecord @private @param {Object} hash @return {DS.Model} record */ createRecord: function(hash) { var owner = get(this, 'owner'), store = get(owner, 'store'), type = get(this, 'type'), record; record = store.createRecord.call(store, type, hash); this.pushObject(record); return record; } }); __exports__["default"] = ManyArray; }); define("ember-data/lib/system/record_arrays/record_array", ["../store","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var PromiseArray = __dependency1__.PromiseArray; var get = Ember.get, set = Ember.set; /** A record array is an array that contains records of a certain type. The record array materializes records as needed when they are retrieved for the first time. You should not create record arrays yourself. Instead, an instance of `DS.RecordArray` or its subclasses will be returned by your application's store in response to queries. @class RecordArray @namespace DS @extends Ember.ArrayProxy @uses Ember.Evented */ var RecordArray = Ember.ArrayProxy.extend(Ember.Evented, { /** The model type contained by this record array. @property type @type DS.Model */ type: null, /** The array of client ids backing the record array. When a record is requested from the record array, the record for the client id at the same index is materialized, if necessary, by the store. @property content @private @type Ember.Array */ content: null, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all('person'); people.get('isLoaded'); // true ``` @property isLoaded @type Boolean */ isLoaded: false, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all('person'); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @property isUpdating @type Boolean */ isUpdating: false, /** The store that created this record array. @property store @private @type DS.Store */ store: null, /** Retrieves an object from the content by index. @method objectAtContent @private @param {Number} index @return {DS.Model} record */ objectAtContent: function(index) { var content = get(this, 'content'); return content.objectAt(index); }, /** Used to get the latest version of all of the records in this array from the adapter. Example ```javascript var people = store.all('person'); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @method update */ update: function() { if (get(this, 'isUpdating')) { return; } var store = get(this, 'store'), type = get(this, 'type'); return store.fetchAll(type, this); }, /** Adds a record to the `RecordArray`. @method addRecord @private @param {DS.Model} record */ addRecord: function(record) { get(this, 'content').addObject(record); }, /** Removes a record to the `RecordArray`. @method removeRecord @private @param {DS.Model} record */ removeRecord: function(record) { get(this, 'content').removeObject(record); }, /** Saves all of the records in the `RecordArray`. Example ```javascript var messages = store.all('message'); messages.forEach(function(message) { message.set('hasBeenSeen', true); }); messages.save(); ``` @method save @return {DS.PromiseArray} promise */ save: function() { var promiseLabel = "DS: RecordArray#save " + get(this, 'type'); var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) { return Ember.A(array); }, null, "DS: RecordArray#save apply Ember.NativeArray"); return PromiseArray.create({ promise: promise }); }, _dissociateFromOwnRecords: function() { var array = this; this.forEach(function(record){ var recordArrays = record._recordArrays; if (recordArrays) { recordArrays.remove(array); } }); }, willDestroy: function(){ this._dissociateFromOwnRecords(); this._super(); } }); __exports__["default"] = RecordArray; }); define("ember-data/lib/system/relationship-meta", ["../../../ember-inflector/lib/system","exports"], function(__dependency1__, __exports__) { "use strict"; var singularize = __dependency1__.singularize; function typeForRelationshipMeta(store, meta) { var typeKey, type; typeKey = meta.type || meta.key; if (typeof typeKey === 'string') { if (meta.kind === 'hasMany') { typeKey = singularize(typeKey); } type = store.modelFor(typeKey); } else { type = meta.type; } return type; } __exports__.typeForRelationshipMeta = typeForRelationshipMeta;function relationshipFromMeta(store, meta) { return { key: meta.key, kind: meta.kind, type: typeForRelationshipMeta(store, meta), options: meta.options, parentType: meta.parentType, isRelationship: true }; } __exports__.relationshipFromMeta = relationshipFromMeta; }); define("ember-data/lib/system/relationships", ["./relationships/belongs_to","./relationships/has_many","../system/relationships/ext","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; /** @module ember-data */ var belongsTo = __dependency1__["default"]; var hasMany = __dependency2__["default"]; __exports__.belongsTo = belongsTo; __exports__.hasMany = hasMany; }); define("ember-data/lib/system/relationships/belongs_to", ["../model","../store","../changes","../relationship-meta","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; var get = Ember.get, set = Ember.set, isNone = Ember.isNone; var Promise = Ember.RSVP.Promise; var Model = __dependency1__.Model; var PromiseObject = __dependency2__.PromiseObject; var RelationshipChange = __dependency3__.RelationshipChange; var relationshipFromMeta = __dependency4__.relationshipFromMeta; var typeForRelationshipMeta = __dependency4__.typeForRelationshipMeta; /** @module ember-data */ function asyncBelongsTo(type, options, meta) { return Ember.computed('data', function(key, value) { var data = get(this, 'data'), store = get(this, 'store'), promiseLabel = "DS: Async belongsTo " + this + " : " + key, promise; meta.key = key; if (arguments.length === 2) { return value === undefined ? null : PromiseObject.create({ promise: Promise.cast(value, promiseLabel) }); } var link = data.links && data.links[key], belongsTo = data[key]; if(!isNone(belongsTo)) { promise = store.fetchRecord(belongsTo) || Promise.cast(belongsTo, promiseLabel); return PromiseObject.create({ promise: promise }); } else if (link) { promise = store.findBelongsTo(this, link, relationshipFromMeta(store, meta)); return PromiseObject.create({ promise: promise }); } else { return null; } }).meta(meta); } /** `DS.belongsTo` is used to define One-To-One and One-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.belongsTo` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses) #### One-To-One To declare a one-to-one relationship between two models, use `DS.belongsTo`: ```javascript App.User = DS.Model.extend({ profile: DS.belongsTo('profile') }); App.Profile = DS.Model.extend({ user: DS.belongsTo('user') }); ``` #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` @namespace @method belongsTo @for DS @param {String or DS.Model} type the model type of the relationship @param {Object} options a hash of options @return {Ember.computed} relationship */ function belongsTo(type, options) { if (typeof type === 'object') { options = type; type = undefined; } else { } options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo', key: null }; if (options.async) { return asyncBelongsTo(type, options, meta); } return Ember.computed('data', function(key, value) { var data = get(this, 'data'), store = get(this, 'store'), belongsTo, typeClass; if (typeof type === 'string') { typeClass = store.modelFor(type); } else { typeClass = type; } if (arguments.length === 2) { return value === undefined ? null : value; } belongsTo = data[key]; if (isNone(belongsTo)) { return null; } store.fetchRecord(belongsTo); return belongsTo; }).meta(meta); } /** These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. @class Model @namespace DS */ Model.reopen({ /** @method belongsToWillChange @private @static @param record @param key */ belongsToWillChange: Ember.beforeObserver(function(record, key) { if (get(record, 'isLoaded')) { var oldParent = get(record, key); if (oldParent) { var store = get(record, 'store'), change = RelationshipChange.createChange(record, oldParent, store, { key: key, kind: "belongsTo", changeType: "remove" }); change.sync(); this._changesToSync[key] = change; } } }), /** @method belongsToDidChange @private @static @param record @param key */ belongsToDidChange: Ember.immediateObserver(function(record, key) { if (get(record, 'isLoaded')) { var newParent = get(record, key); if (newParent) { var store = get(record, 'store'), change = RelationshipChange.createChange(record, newParent, store, { key: key, kind: "belongsTo", changeType: "add" }); change.sync(); } } delete this._changesToSync[key]; }) }); __exports__["default"] = belongsTo; }); define("ember-data/lib/system/relationships/ext", ["../../../../ember-inflector/lib/system","../relationship-meta","../model"], function(__dependency1__, __dependency2__, __dependency3__) { "use strict"; var singularize = __dependency1__.singularize; var typeForRelationshipMeta = __dependency2__.typeForRelationshipMeta; var relationshipFromMeta = __dependency2__.relationshipFromMeta; var Model = __dependency3__.Model; var get = Ember.get, set = Ember.set; /** @module ember-data */ /* This file defines several extensions to the base `DS.Model` class that add support for one-to-many relationships. */ /** @class Model @namespace DS */ Model.reopen({ /** This Ember.js hook allows an object to be notified when a property is defined. In this case, we use it to be notified when an Ember Data user defines a belongs-to relationship. In that case, we need to set up observers for each one, allowing us to track relationship changes and automatically reflect changes in the inverse has-many array. This hook passes the class being set up, as well as the key and value being defined. So, for example, when the user does this: ```javascript DS.Model.extend({ parent: DS.belongsTo('user') }); ``` This hook would be called with "parent" as the key and the computed property returned by `DS.belongsTo` as the value. @method didDefineProperty @param proto @param key @param value */ didDefineProperty: function(proto, key, value) { // Check if the value being set is a computed property. if (value instanceof Ember.Descriptor) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value.meta(); if (meta.isRelationship && meta.kind === 'belongsTo') { Ember.addObserver(proto, key, null, 'belongsToDidChange'); Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange'); } meta.parentType = proto.constructor; } } }); /* These DS.Model extensions add class methods that provide relationship introspection abilities about relationships. A note about the computed properties contained here: **These properties are effectively sealed once called for the first time.** To avoid repeatedly doing expensive iteration over a model's fields, these values are computed once and then cached for the remainder of the runtime of your application. If your application needs to modify a class after its initial definition (for example, using `reopen()` to add additional attributes), make sure you do it before using your model with the store, which uses these properties extensively. */ Model.reopenClass({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); ``` Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. @method typeForRelationship @static @param {String} name the name of the relationship @return {subclass of DS.Model} the type of the relationship, or undefined */ typeForRelationship: function(name) { var relationship = get(this, 'relationshipsByName').get(name); return relationship && relationship.type; }, inverseFor: function(name) { var inverseType = this.typeForRelationship(name); if (!inverseType) { return null; } var options = this.metaForProperty(name).options; if (options.inverse === null) { return null; } var inverseName, inverseKind; if (options.inverse) { inverseName = options.inverse; inverseKind = Ember.get(inverseType, 'relationshipsByName').get(inverseName).kind; } else { var possibleRelationships = findPossibleInverses(this, inverseType); if (possibleRelationships.length === 0) { return null; } inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } function findPossibleInverses(type, inverseType, possibleRelationships) { possibleRelationships = possibleRelationships || []; var relationshipMap = get(inverseType, 'relationships'); if (!relationshipMap) { return; } var relationships = relationshipMap.get(type); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationshipMap.get(type)); } if (type.superclass) { findPossibleInverses(type.superclass, inverseType, possibleRelationships); } return possibleRelationships; } return { type: inverseType, name: inverseName, kind: inverseKind }; }, /** The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type. For example, given the following model definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This computed property would return a map describing these relationships, like this: ```javascript var relationships = Ember.get(App.Blog, 'relationships'); relationships.get(App.User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(App.Post); //=> [ { name: 'posts', kind: 'hasMany' } ] ``` @property relationships @static @type Ember.Map @readOnly */ relationships: Ember.computed(function() { var map = new Ember.MapWithDefault({ defaultValue: function() { return []; } }); // Loop through each computed property on the class this.eachComputedProperty(function(name, meta) { // If the computed property is a relationship, add // it to the map. if (meta.isRelationship) { meta.key = name; var relationshipsForType = map.get(typeForRelationshipMeta(this.store, meta)); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }).cacheable(false), /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipNames = Ember.get(App.Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] ``` @property relationshipNames @static @type Object @readOnly */ relationshipNames: Ember.computed(function() { var names = { hasMany: [], belongsTo: [] }; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { names[meta.kind].push(name); } }); return names; }), /** An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relatedTypes = Ember.get(App.Blog, 'relatedTypes'); //=> [ App.User, App.Post ] ``` @property relatedTypes @static @type Ember.Array @readOnly */ relatedTypes: Ember.computed(function() { var type, types = Ember.A(); // Loop through each computed property on the class, // and create an array of the unique types involved // in relationships this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; type = typeForRelationshipMeta(this.store, meta); if (!types.contains(type)) { types.push(type); } } }); return types; }).cacheable(false), /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: App.User } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: App.User } ``` @property relationshipsByName @static @type Ember.Map @readOnly */ relationshipsByName: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; var relationship = relationshipFromMeta(this.store, meta); relationship.type = typeForRelationshipMeta(this.store, meta); map.set(name, relationship); } }); return map; }).cacheable(false), /** A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships. For example: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post'), title: DS.attr('string') }); var fields = Ember.get(App.Blog, 'fields'); fields.forEach(function(field, kind) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute ``` @property fields @static @type Ember.Map @readOnly */ fields: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { map.set(name, meta.kind); } else if (meta.isAttribute) { map.set(name, 'attribute'); } }); return map; }), /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { get(this, 'relationshipsByName').forEach(function(name, relationship) { callback.call(binding, name, relationship); }); }, /** Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model. @method eachRelatedType @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelatedType: function(callback, binding) { get(this, 'relatedTypes').forEach(function(type) { callback.call(binding, type); }); } }); Model.reopen({ /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { this.constructor.eachRelationship(callback, binding); } }); }); define("ember-data/lib/system/relationships/has_many", ["../store","../relationship-meta","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var PromiseArray = __dependency1__.PromiseArray; var get = Ember.get, set = Ember.set, setProperties = Ember.setProperties; var relationshipFromMeta = __dependency2__.relationshipFromMeta; var typeForRelationshipMeta = __dependency2__.typeForRelationshipMeta; function asyncHasMany(type, options, meta) { return Ember.computed('data', function(key) { var relationship = this._relationships[key], promiseLabel = "DS: Async hasMany " + this + " : " + key; meta.key = key; if (!relationship) { var resolver = Ember.RSVP.defer(promiseLabel); relationship = buildRelationship(this, key, options, function(store, data) { var link = data.links && data.links[key]; var rel; if (link) { rel = store.findHasMany(this, link, relationshipFromMeta(store, meta), resolver); } else { rel = store.findMany(this, data[key], typeForRelationshipMeta(store, meta), resolver); } // cache the promise so we can use it // when we come back and don't need to rebuild // the relationship. set(rel, 'promise', resolver.promise); return rel; }); } var promise = relationship.get('promise').then(function() { return relationship; }, null, "DS: Async hasMany records received"); return PromiseArray.create({ promise: promise }); }).meta(meta).readOnly(); } function buildRelationship(record, key, options, callback) { var rels = record._relationships; if (rels[key]) { return rels[key]; } var data = get(record, 'data'), store = get(record, 'store'); var relationship = rels[key] = callback.call(record, store, data); return setProperties(relationship, { owner: record, name: key, isPolymorphic: options.polymorphic }); } function hasRelationship(type, options) { options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany', key: null }; if (options.async) { return asyncHasMany(type, options, meta); } return Ember.computed('data', function(key) { return buildRelationship(this, key, options, function(store, data) { var records = data[key]; return store.findMany(this, data[key], typeForRelationshipMeta(store, meta)); }); }).meta(meta).readOnly(); } /** `DS.hasMany` is used to define One-To-Many and Many-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.hasMany` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model. #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` #### Many-To-Many To declare a many-to-many relationship between two models, use `DS.hasMany`: ```javascript App.Post = DS.Model.extend({ tags: DS.hasMany('tag') }); App.Tag = DS.Model.extend({ posts: DS.hasMany('post') }); ``` #### Explicit Inverses Ember Data will do its best to discover which relationships map to one another. In the one-to-many code above, for example, Ember Data can figure out that changing the `comments` relationship should update the `post` relationship on the inverse because post is the only relationship to that model. However, sometimes you may have multiple `belongsTo`/`hasManys` for the same type. You can specify which property on the related model is the inverse using `DS.hasMany`'s `inverse` option: ```javascript var belongsTo = DS.belongsTo, hasMany = DS.hasMany; App.Comment = DS.Model.extend({ onePost: belongsTo('post'), twoPost: belongsTo('post'), redPost: belongsTo('post'), bluePost: belongsTo('post') }); App.Post = DS.Model.extend({ comments: hasMany('comment', { inverse: 'redPost' }) }); ``` You can also specify an inverse on a `belongsTo`, which works how you'd expect. @namespace @method hasMany @for DS @param {String or DS.Model} type the model type of the relationship @param {Object} options a hash of options @return {Ember.computed} relationship */ function hasMany(type, options) { if (typeof type === 'object') { options = type; type = undefined; } return hasRelationship(type, options); } __exports__["default"] = hasMany; }); define("ember-data/lib/system/store", ["./adapter","ember-inflector/lib/system/string","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /*globals Ember*/ /*jshint eqnull:true*/ /** @module ember-data */ var InvalidError = __dependency1__.InvalidError; var Adapter = __dependency1__.Adapter; var singularize = __dependency2__.singularize; var get = Ember.get, set = Ember.set; var once = Ember.run.once; var isNone = Ember.isNone; var forEach = Ember.EnumerableUtils.forEach; var indexOf = Ember.EnumerableUtils.indexOf; var map = Ember.EnumerableUtils.map; var Promise = Ember.RSVP.Promise; var copy = Ember.copy; var Store, PromiseObject, PromiseArray, RecordArrayManager, Model; var camelize = Ember.String.camelize; // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. These are always coerced to be strings // before being used internally. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +reference+ means a record reference object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a subclass of DS.Model. // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`), // it is important that internally we use strings, since IDs may be serialized // and lose type information. For example, Ember's router may put a record's // ID into the URL, and if we later try to deserialize that URL and find the // corresponding record, we will not know if it is a string or a number. function coerceId(id) { return id == null ? null : id+''; } /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of `DS.Model` that wrap the individual data for a record, so that they can be bound to in your Handlebars templates. Define your application's store like this: ```javascript MyApp.Store = DS.Store.extend(); ``` Most Ember.js applications will only have a single `DS.Store` that is automatically created by their `Ember.Application`. You can retrieve models from the store in several ways. To retrieve a record for a specific id, use `DS.Store`'s `find()` method: ```javascript var person = store.find('person', 123); ``` If your application has multiple `DS.Store` instances (an unusual case), you can specify which store should be used: ```javascript var person = store.find('person', 123); ``` By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: ```javascript MyApp.store = DS.Store.create({ adapter: 'MyApp.CustomAdapter' }); ``` You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. ### Store createRecord() vs. push() vs. pushPayload() vs. update() The store provides multiple ways to create new records object. They have some subtle differences in their use which are detailed below: [createRecord](#method_createRecord) is used for creating new records on the client side. This will return a new record in the `created.uncommitted` state. In order to persist this record to the backend you will need to call `record.save()`. [push](#method_push) is used to notify Ember Data's store of new or updated records that exist in the backend. This will return a record in the `loaded.saved` state. The primary use-case for `store#push` is to notify Ember Data about record updates that happen outside of the normal adapter methods (for example [SSE](http://dev.w3.org/html5/eventsource/) or [Web Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)). [pushPayload](#method_pushPayload) is a convenience wrapper for `store#push` that will deserialize payloads if the Serializer implements a `pushPayload` method. [update](#method_update) works like `push`, except it can handle partial attributes without overwriting the existing record properties. Note: When creating a new record using any of the above methods Ember Data will update `DS.RecordArray`s such as those returned by `store#all()`, `store#findAll()` or `store#filter()`. This means any data bindings or computed properties that depend on the RecordArray will automatically be synced to include the new or updated record values. @class Store @namespace DS @extends Ember.Object */ Store = Ember.Object.extend({ /** @method init @private */ init: function() { // internal bookkeeping; not observable if (!RecordArrayManager) { RecordArrayManager = requireModule("ember-data/lib/system/record_array_manager")["default"]; } this.typeMaps = {}; this.recordArrayManager = RecordArrayManager.create({ store: this }); this._relationshipChanges = {}; this._pendingSave = []; }, /** The adapter to use to communicate to a backend server or other persistence layer. This can be specified as an instance, class, or string. If you want to specify `App.CustomAdapter` as a string, do: ```js adapter: 'custom' ``` @property adapter @default DS.RESTAdapter @type {DS.Adapter|String} */ adapter: '-rest', /** Returns a JSON representation of the record using a custom type-specific serializer, if one exists. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @method serialize @private @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function(record, options) { return this.serializerFor(record.constructor.typeKey).serialize(record, options); }, /** This property returns the adapter, after resolving a possible string key. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @property defaultAdapter @private @return DS.Adapter */ defaultAdapter: Ember.computed('adapter', function() { var adapter = get(this, 'adapter'); if (typeof adapter === 'string') { adapter = this.container.lookup('adapter:' + adapter) || this.container.lookup('adapter:application') || this.container.lookup('adapter:-rest'); } if (DS.Adapter.detect(adapter)) { adapter = adapter.create({ container: this.container }); } return adapter; }), // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. To create a new instance of `App.Post`: ```js store.createRecord('post', { title: "Rails is omakase" }); ``` @method createRecord @param {String} type @param {Object} properties a hash of properties to set on the newly created record. @return {DS.Model} record */ createRecord: function(type, properties) { type = this.modelFor(type); properties = copy(properties) || {}; // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if (isNone(properties.id)) { properties.id = this._generateId(type); } // Coerce ID to a string properties.id = coerceId(properties.id); var record = this.buildRecord(type, properties.id); // Move the record out of its initial `empty` state into // the `loaded` state. record.loadedData(); // Set the properties specified on the record. record.setProperties(properties); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method _generateId @private @param {String} type @return {String} if the adapter can generate one, an ID */ _generateId: function(type) { var adapter = this.adapterFor(type); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this); } return null; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. Example ```javascript var post = store.createRecord('post', { title: "Rails is omakase" }); store.deleteRecord(post); ``` @method deleteRecord @param {DS.Model} record */ deleteRecord: function(record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. Only non-dirty records can be unloaded. Example ```javascript store.find('post', 1).then(function(post) { store.unloadRecord(post); }); ``` @method unloadRecord @param {DS.Model} record */ unloadRecord: function(record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** This is the main entry point into finding records. The first parameter to this method is the model's name as a string. --- To find a record by ID, pass the `id` as the second parameter: ```javascript store.find('person', 1); ``` The `find` method will always return a **promise** that will be resolved with the record. If the record was already in the store, the promise will be resolved immediately. Otherwise, the store will ask the adapter's `find` method to find the necessary data. The `find` method will always resolve its promise with the same object for a given type and `id`. --- To find all records for a type, call `find` with no additional parameters: ```javascript store.find('person'); ``` This will ask the adapter's `findAll` method to find the records for the given type, and return a promise that will be resolved once the server returns the values. --- To find a record by a query, call `find` with a hash as the second parameter: ```javascript store.find('person', { page: 1 }); ``` This will ask the adapter's `findQuery` method to find the records for the query, and return a promise that will be resolved once the server responds. @method find @param {String or subclass of DS.Model} type @param {Object|String|Integer|null} id @return {Promise} promise */ find: function(type, id) { if (arguments.length === 1) { return this.findAll(type); } // We are passed a query instead of an id. if (Ember.typeOf(id) === 'object') { return this.findQuery(type, id); } return this.findById(type, coerceId(id)); }, /** This method returns a record for a given type and id combination. @method findById @private @param {String or subclass of DS.Model} type @param {String|Integer} id @return {Promise} promise */ findById: function(type, id) { type = this.modelFor(type); var record = this.recordForId(type, id); var fetchedRecord = this.fetchRecord(record); return promiseObject(fetchedRecord || record, "DS: Store#findById " + type + " with id: " + id); }, /** This method makes a series of requests to the adapter's `find` method and returns a promise that resolves once they are all loaded. @private @method findByIds @param {String} type @param {Array} ids @return {Promise} promise */ findByIds: function(type, ids) { var store = this; var promiseLabel = "DS: Store#findByIds " + type; return promiseArray(Ember.RSVP.all(map(ids, function(id) { return store.findById(type, id); })).then(Ember.A, null, "DS: Store#findByIds of " + type + " complete")); }, /** This method is called by `findById` if it discovers that a particular type/id pair hasn't been loaded yet to kick off a request to the adapter. @method fetchRecord @private @param {DS.Model} record @return {Promise} promise */ fetchRecord: function(record) { if (isNone(record)) { return null; } if (record._loadingPromise) { return record._loadingPromise; } if (!get(record, 'isEmpty')) { return null; } var type = record.constructor, id = get(record, 'id'); var adapter = this.adapterFor(type); var promise = _find(adapter, this, type, id); record.loadingData(promise); return promise; }, /** Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it's available. Otherwise, it will return null. ```js var post = store.getById('post', 1); ``` @method getById @param {String or subclass of DS.Model} type @param {String|Integer} id @param {DS.Model} record */ getById: function(type, id) { if (this.hasRecordForId(type, id)) { return this.recordForId(type, id); } else { return null; } }, /** This method is called by the record's `reload` method. This method calls the adapter's `find` method, which returns a promise. When **that** promise resolves, `reloadRecord` will resolve the promise returned by the record's `reload`. @method reloadRecord @private @param {DS.Model} record @return {Promise} promise */ reloadRecord: function(record) { var type = record.constructor, adapter = this.adapterFor(type), id = get(record, 'id'); return _find(adapter, this, type, id); }, /** This method takes a list of records, groups the records by type, converts the records into IDs, and then invokes the adapter's `findMany` method. The records are grouped by type to invoke `findMany` on adapters for each unique type in records. It is used both by a brand new relationship (via the `findMany` method) or when the data underlying an existing relationship changes. @method fetchMany @private @param {Array} records @param {DS.Model} owner @return {Promise} promise */ fetchMany: function(records, owner) { if (!records.length) { return Ember.RSVP.resolve(records); } // Group By Type var recordsByTypeMap = Ember.MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); forEach(records, function(record) { recordsByTypeMap.get(record.constructor).push(record); }); var promises = []; forEach(recordsByTypeMap, function(type, records) { var ids = records.mapProperty('id'), adapter = this.adapterFor(type); promises.push(_findMany(adapter, this, type, ids, owner)); }, this); return Ember.RSVP.all(promises); }, /** Returns true if a record for a given type and ID is already loaded. @method hasRecordForId @param {String or subclass of DS.Model} type @param {String|Integer} id @return {Boolean} */ hasRecordForId: function(type, id) { id = coerceId(id); type = this.modelFor(type); return !!this.typeMapFor(type).idToRecord[id]; }, /** Returns id record for a given type and ID. If one isn't already loaded, it builds a new record and leaves it in the `empty` state. @method recordForId @private @param {String or subclass of DS.Model} type @param {String|Integer} id @return {DS.Model} record */ recordForId: function(type, id) { type = this.modelFor(type); id = coerceId(id); var record = this.typeMapFor(type).idToRecord[id]; if (!record) { record = this.buildRecord(type, id); } return record; }, /** @method findMany @private @param {DS.Model} owner @param {Array} records @param {String or subclass of DS.Model} type @param {Resolver} resolver @return {DS.ManyArray} records */ findMany: function(owner, records, type, resolver) { type = this.modelFor(type); records = Ember.A(records); var unloadedRecords = records.filterProperty('isEmpty', true), manyArray = this.recordArrayManager.createManyArray(type, records); forEach(unloadedRecords, function(record) { record.loadingData(); }); manyArray.loadingRecordsCount = unloadedRecords.length; if (unloadedRecords.length) { forEach(unloadedRecords, function(record) { this.recordArrayManager.registerWaitingRecordArray(record, manyArray); }, this); resolver.resolve(this.fetchMany(unloadedRecords, owner)); } else { if (resolver) { resolver.resolve(); } manyArray.set('isLoaded', true); once(manyArray, 'trigger', 'didLoad'); } return manyArray; }, /** If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched. The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants. The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship. @method findHasMany @private @param {DS.Model} owner @param {any} link @param {String or subclass of DS.Model} type @return {Promise} promise */ findHasMany: function(owner, link, relationship, resolver) { var adapter = this.adapterFor(owner.constructor); var records = this.recordArrayManager.createManyArray(relationship.type, Ember.A([])); resolver.resolve(_findHasMany(adapter, this, owner, link, relationship)); return records; }, /** @method findBelongsTo @private @param {DS.Model} owner @param {any} link @param {Relationship} relationship @return {Promise} promise */ findBelongsTo: function(owner, link, relationship) { var adapter = this.adapterFor(owner.constructor); return _findBelongsTo(adapter, this, owner, link, relationship); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. This method returns a promise, which is resolved with a `RecordArray` once the server returns. @method findQuery @private @param {String or subclass of DS.Model} type @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ findQuery: function(type, query) { type = this.modelFor(type); var array = this.recordArrayManager .createAdapterPopulatedRecordArray(type, query); var adapter = this.adapterFor(type); return promiseArray(_findQuery(adapter, this, type, query, array)); }, /** This method returns an array of all records adapter can find. It triggers the adapter's `findAll` method to give it an opportunity to populate the array with records of that type. @method findAll @private @param {String or subclass of DS.Model} type @return {DS.AdapterPopulatedRecordArray} */ findAll: function(type) { type = this.modelFor(type); return this.fetchAll(type, this.all(type)); }, /** @method fetchAll @private @param {DS.Model} type @param {DS.RecordArray} array @return {Promise} promise */ fetchAll: function(type, array) { var adapter = this.adapterFor(type), sinceToken = this.typeMapFor(type).metadata.since; set(array, 'isUpdating', true); return promiseArray(_findAll(adapter, this, type, sinceToken)); }, /** @method didUpdateAll @param {DS.Model} type */ didUpdateAll: function(type) { var findAllCache = this.typeMapFor(type).findAllCache; set(findAllCache, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type. Note that because it's just a filter, it will have any locally created records of the type. Also note that multiple calls to `all` for a given type will always return the same RecordArray. Example ```javascript var localPosts = store.all('post'); ``` @method all @param {String or subclass of DS.Model} type @return {DS.RecordArray} */ all: function(type) { type = this.modelFor(type); var typeMap = this.typeMapFor(type), findAllCache = typeMap.findAllCache; if (findAllCache) { return findAllCache; } var array = this.recordArrayManager.createRecordArray(type); typeMap.findAllCache = array; return array; }, /** This method unloads all of the known records for a given type. ```javascript store.unloadAll('post'); ``` @method unloadAll @param {String or subclass of DS.Model} type */ unloadAll: function(type) { var modelType = this.modelFor(type); var typeMap = this.typeMapFor(modelType); var records = typeMap.records.slice(); var record; for (var i = 0; i < records.length; i++) { record = records[i]; record.unloadRecord(); record.destroy(); // maybe within unloadRecord } typeMap.findAllCache = null; }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The callback function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. Optionally you can pass a query which will be triggered at first. The results returned by the server could then appear in the filter if they match the filter function. Example ```javascript store.filter('post', {unread: true}, function(post) { return post.get('unread'); }).then(function(unreadPosts) { unreadPosts.get('length'); // 5 var unreadPost = unreadPosts.objectAt(0); unreadPost.set('unread', false); unreadPosts.get('length'); // 4 }); ``` @method filter @param {String or subclass of DS.Model} type @param {Object} query optional query @param {Function} filter @return {DS.PromiseArray} */ filter: function(type, query, filter) { var promise; var length = arguments.length; var array; var hasQuery = length === 3; // allow an optional server query if (hasQuery) { promise = this.findQuery(type, query); } else if (arguments.length === 2) { filter = query; } type = this.modelFor(type); if (hasQuery) { array = this.recordArrayManager.createFilteredRecordArray(type, filter, query); } else { array = this.recordArrayManager.createFilteredRecordArray(type, filter); } promise = promise || Promise.cast(array); return promiseArray(promise.then(function() { return array; }, null, "DS: Store#filter of " + type)); }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit. Example ```javascript store.recordIsLoaded('post', 1); // false store.find('post', 1).then(function() { store.recordIsLoaded('post', 1); // true }); ``` @method recordIsLoaded @param {String or subclass of DS.Model} type @param {string} id @return {boolean} */ recordIsLoaded: function(type, id) { if (!this.hasRecordForId(type, id)) { return false; } return !get(this.recordForId(type, id), 'isEmpty'); }, /** This method returns the metadata for a specific type. @method metadataFor @param {String or subclass of DS.Model} type @return {object} */ metadataFor: function(type) { type = this.modelFor(type); return this.typeMapFor(type).metadata; }, // ............ // . UPDATING . // ............ /** If the adapter updates attributes or acknowledges creation or deletion, the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @method dataWasUpdated @private @param {Class} type @param {DS.Model} record */ dataWasUpdated: function(type, record) { this.recordArrayManager.recordDidChange(record); }, // .............. // . PERSISTING . // .............. /** This method is called by `record.save`, and gets passed a resolver for the promise that `record.save` returns. It schedules saving to happen at the end of the run loop. @method scheduleSave @private @param {DS.Model} record @param {Resolver} resolver */ scheduleSave: function(record, resolver) { record.adapterWillCommit(); this._pendingSave.push([record, resolver]); once(this, 'flushPendingSave'); }, /** This method is called at the end of the run loop, and flushes any records passed into `scheduleSave` @method flushPendingSave @private */ flushPendingSave: function() { var pending = this._pendingSave.slice(); this._pendingSave = []; forEach(pending, function(tuple) { var record = tuple[0], resolver = tuple[1], adapter = this.adapterFor(record.constructor), operation; if (get(record, 'currentState.stateName') === 'root.deleted.saved') { return resolver.resolve(record); } else if (get(record, 'isNew')) { operation = 'createRecord'; } else if (get(record, 'isDeleted')) { operation = 'deleteRecord'; } else { operation = 'updateRecord'; } resolver.resolve(_commit(adapter, this, operation, record)); }, this); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is resolved. If the data provides a server-generated ID, it will update the record and the store's indexes. @method didSaveRecord @private @param {DS.Model} record the in-flight record @param {Object} data optional data (see above) */ didSaveRecord: function(record, data) { if (data) { // normalize relationship IDs into records data = normalizeRelationships(this, record.constructor, data, record); this.updateId(record, data); } record.adapterDidCommit(data); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected with a `DS.InvalidError`. @method recordWasInvalid @private @param {DS.Model} record @param {Object} errors */ recordWasInvalid: function(record, errors) { record.adapterDidInvalidate(errors); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected (with anything other than a `DS.InvalidError`). @method recordWasError @private @param {DS.Model} record */ recordWasError: function(record) { record.adapterDidError(); }, /** When an adapter's `createRecord`, `updateRecord` or `deleteRecord` resolves with data, this method extracts the ID from the supplied data. @method updateId @private @param {DS.Model} record @param {Object} data */ updateId: function(record, data) { var oldId = get(record, 'id'), id = coerceId(data.id); this.typeMapFor(record.constructor).idToRecord[id] = record; set(record, 'id', id); }, /** Returns a map of IDs to client IDs for a given type. @method typeMapFor @private @param type @return {Object} typeMap */ typeMapFor: function(type) { var typeMaps = get(this, 'typeMaps'), guid = Ember.guidFor(type), typeMap; typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: {}, records: [], metadata: {}, type: type }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {String or subclass of DS.Model} type @param {Object} data @param {Boolean} partial the data should be merged into the existing data, not replace it. */ _load: function(type, data, partial) { var id = coerceId(data.id), record = this.recordForId(type, id); record.setupData(data, partial); this.recordArrayManager.recordDidChange(record); return record; }, /** Returns a model class for a particular key. Used by methods that take a type key (like `find`, `createRecord`, etc.) @method modelFor @param {String or subclass of DS.Model} key @return {subclass of DS.Model} */ modelFor: function(key) { var factory; if (typeof key === 'string') { var normalizedKey = this.container.normalize('model:' + key); factory = this.container.lookupFactory(normalizedKey); if (!factory) { throw new Ember.Error("No model was found for '" + key + "'"); } factory.typeKey = this._normalizeTypeKey(normalizedKey.split(':', 2)[1]); } else { // A factory already supplied. Ensure it has a normalized key. factory = key; if (factory.typeKey) { factory.typeKey = this._normalizeTypeKey(factory.typeKey); } } factory.store = this; return factory; }, /** Push some data for a given type into the store. This method expects normalized data: * The ID is a key named `id` (an ID is mandatory) * The names of attributes are the ones you used in your model's `DS.attr`s. * Your relationships must be: * represented as IDs or Arrays of IDs * represented as model instances * represented as URLs, under the `links` key For this model: ```js App.Person = DS.Model.extend({ firstName: DS.attr(), lastName: DS.attr(), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { id: 1, firstName: "Tom", lastName: "Dale", children: [1, 2, 3] } ``` To represent the children relationship as a URL: ```js { id: 1, firstName: "Tom", lastName: "Dale", links: { children: "/people/1/children" } } ``` If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. This method can be used both to push in brand new records, as well as to update existing records. @method push @param {String or subclass of DS.Model} type @param {Object} data @return {DS.Model} the record that was created or updated. */ push: function(type, data, _partial) { // _partial is an internal param used by `update`. // If passed, it means that the data should be // merged into the existing data, not replace it. type = this.modelFor(type); // normalize relationship IDs into records data = normalizeRelationships(this, type, data); this._load(type, data, _partial); return this.recordForId(type, data.id); }, /** Push some raw data into the store. This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer. ```js App.ApplicationSerializer = DS.ActiveModelSerializer; var pushData = { posts: [ {id: 1, post_title: "Great post", comment_ids: [2]} ], comments: [ {id: 2, comment_body: "Insightful comment"} ] } store.pushPayload(pushData); ``` By default, the data will be deserialized using a default serializer (the application serializer if it exists). Alternativly, `pushPayload` will accept a model type which will determine which serializer will process the payload. However, the serializer itself (processing this data via `normalizePayload`) will not know which model it is deserializing. ```js App.ApplicationSerializer = DS.ActiveModelSerializer; App.PostSerializer = DS.JSONSerializer; store.pushPayload('comment', pushData); // Will use the ApplicationSerializer store.pushPayload('post', pushData); // Will use the PostSerializer ``` @method pushPayload @param {String} type Optionally, a model used to determine which serializer will be used @param {Object} payload */ pushPayload: function (type, payload) { var serializer; if (!payload) { payload = type; serializer = defaultSerializer(this.container); } else { serializer = this.serializerFor(type); } serializer.pushPayload(this, payload); }, /** Update existing records in the store. Unlike [push](#method_push), update will merge the new data properties with the existing properties. This makes it safe to use with a subset of record attributes. This method expects normalized data. `update` is useful if you app broadcasts partial updates to records. ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string') }); store.get('person', 1).then(function(tom) { tom.get('firstName'); // Tom tom.get('lastName'); // Dale var updateEvent = {id: 1, firstName: "TomHuda"}; store.update('person', updateEvent); tom.get('firstName'); // TomHuda tom.get('lastName'); // Dale }); ``` @method update @param {String} type @param {Object} data @return {DS.Model} the record that was updated. */ update: function(type, data) { return this.push(type, data, true); }, /** If you have an Array of normalized data to push, you can call `pushMany` with the Array, and it will call `push` repeatedly for you. @method pushMany @param {String or subclass of DS.Model} type @param {Array} datas @return {Array} */ pushMany: function(type, datas) { return map(datas, function(data) { return this.push(type, data); }, this); }, /** If you have some metadata to set for a type you can call `metaForType`. @method metaForType @param {String or subclass of DS.Model} type @param {Object} metadata */ metaForType: function(type, metadata) { type = this.modelFor(type); Ember.merge(this.typeMapFor(type).metadata, metadata); }, /** Build a brand new record for a given type, ID, and initial data. @method buildRecord @private @param {subclass of DS.Model} type @param {String} id @param {Object} data @return {DS.Model} record */ buildRecord: function(type, id, data) { var typeMap = this.typeMapFor(type), idToRecord = typeMap.idToRecord; // lookupFactory should really return an object that creates // instances with the injections applied var record = type._create({ id: id, store: this, container: this.container }); if (data) { record.setupData(data); } // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToRecord[id] = record; } typeMap.records.push(record); return record; }, // ............... // . DESTRUCTION . // ............... /** When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed. @method dematerializeRecord @private @param {DS.Model} record */ dematerializeRecord: function(record) { var type = record.constructor, typeMap = this.typeMapFor(type), id = get(record, 'id'); record.updateRecordArrays(); if (id) { delete typeMap.idToRecord[id]; } var loc = indexOf(typeMap.records, record); typeMap.records.splice(loc, 1); }, // ........................ // . RELATIONSHIP CHANGES . // ........................ addRelationshipChangeFor: function(childRecord, childKey, parentRecord, parentKey, change) { var clientId = childRecord.clientId, parentClientId = parentRecord ? parentRecord : parentRecord; var key = childKey + parentKey; var changes = this._relationshipChanges; if (!(clientId in changes)) { changes[clientId] = {}; } if (!(parentClientId in changes[clientId])) { changes[clientId][parentClientId] = {}; } if (!(key in changes[clientId][parentClientId])) { changes[clientId][parentClientId][key] = {}; } changes[clientId][parentClientId][key][change.changeType] = change; }, removeRelationshipChangeFor: function(clientRecord, childKey, parentRecord, parentKey, type) { var clientId = clientRecord.clientId, parentClientId = parentRecord ? parentRecord.clientId : parentRecord; var changes = this._relationshipChanges; var key = childKey + parentKey; if (!(clientId in changes) || !(parentClientId in changes[clientId]) || !(key in changes[clientId][parentClientId])){ return; } delete changes[clientId][parentClientId][key][type]; }, relationshipChangePairsFor: function(record){ var toReturn = []; if( !record ) { return toReturn; } //TODO(Igor) What about the other side var changesObject = this._relationshipChanges[record.clientId]; for (var objKey in changesObject){ if(changesObject.hasOwnProperty(objKey)){ for (var changeKey in changesObject[objKey]){ if(changesObject[objKey].hasOwnProperty(changeKey)){ toReturn.push(changesObject[objKey][changeKey]); } } } } return toReturn; }, // ...................... // . PER-TYPE ADAPTERS // ...................... /** Returns the adapter for a given type. @method adapterFor @private @param {subclass of DS.Model} type @return DS.Adapter */ adapterFor: function(type) { var container = this.container, adapter; if (container) { adapter = container.lookup('adapter:' + type.typeKey) || container.lookup('adapter:application'); } return adapter || get(this, 'defaultAdapter'); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. /** Returns an instance of the serializer for a given type. For example, `serializerFor('person')` will return an instance of `App.PersonSerializer`. If no `App.PersonSerializer` is found, this method will look for an `App.ApplicationSerializer` (the default serializer for your entire application). If no `App.ApplicationSerializer` is found, it will fall back to an instance of `DS.JSONSerializer`. @method serializerFor @private @param {String} type the record to serialize @return {DS.Serializer} */ serializerFor: function(type) { type = this.modelFor(type); var adapter = this.adapterFor(type); return serializerFor(this.container, type.typeKey, adapter && adapter.defaultSerializer); }, willDestroy: function() { var typeMaps = this.typeMaps; var keys = Ember.keys(typeMaps); var store = this; var types = map(keys, byType); this.recordArrayManager.destroy(); forEach(types, this.unloadAll, this); function byType(entry) { return typeMaps[entry]['type']; } }, /** All typeKeys are camelCase internally. Changing this function may require changes to other normalization hooks (such as typeForRoot). @method _normalizeTypeKey @private @param {String} type @return {String} if the adapter can generate one, an ID */ _normalizeTypeKey: function(key) { return camelize(singularize(key)); } }); function normalizeRelationships(store, type, data, record) { type.eachRelationship(function(key, relationship) { // A link (usually a URL) was already provided in // normalized form if (data.links && data.links[key]) { if (record && relationship.options.async) { record._relationships[key] = null; } return; } var kind = relationship.kind, value = data[key]; if (value == null) { return; } if (kind === 'belongsTo') { deserializeRecordId(store, data, key, relationship, value); } else if (kind === 'hasMany') { deserializeRecordIds(store, data, key, relationship, value); addUnsavedRecords(record, key, value); } }); return data; } function deserializeRecordId(store, data, key, relationship, id) { if (!Model) { Model = requireModule("ember-data/lib/system/model")["Model"]; } if (isNone(id) || id instanceof Model) { return; } var type; if (typeof id === 'number' || typeof id === 'string') { type = typeFor(relationship, key, data); data[key] = store.recordForId(type, id); } else if (typeof id === 'object') { // polymorphic data[key] = store.recordForId(id.type, id.id); } } function typeFor(relationship, key, data) { if (relationship.options.polymorphic) { return data[key + "Type"]; } else { return relationship.type; } } function deserializeRecordIds(store, data, key, relationship, ids) { for (var i=0, l=ids.length; i<l; i++) { deserializeRecordId(store, ids, i, relationship, ids[i]); } } // If there are any unsaved records that are in a hasMany they won't be // in the payload, so add them back in manually. function addUnsavedRecords(record, key, data) { if(record) { Ember.A(data).pushObjects(record.get(key).filterBy('isNew')); } } // Delegation to the adapter and promise management /** A `PromiseArray` is an object that acts like both an `Ember.Array` and a promise. When the promise is resolved the resulting value will be set to the `PromiseArray`'s `content` property. This makes it easy to create data bindings with the `PromiseArray` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseArray = DS.PromiseArray.create({ promise: $.getJSON('/some/remote/data.json') }); promiseArray.get('length'); // 0 promiseArray.then(function() { promiseArray.get('length'); // 100 }); ``` @class PromiseArray @namespace DS @extends Ember.ArrayProxy @uses Ember.PromiseProxyMixin */ PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin); /** A `PromiseObject` is an object that acts like both an `Ember.Object` and a promise. When the promise is resolved the the resulting value will be set to the `PromiseObject`'s `content` property. This makes it easy to create data bindings with the `PromiseObject` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseObject = DS.PromiseObject.create({ promise: $.getJSON('/some/remote/data.json') }); promiseObject.get('name'); // null promiseObject.then(function() { promiseObject.get('name'); // 'Tomster' }); ``` @class PromiseObject @namespace DS @extends Ember.ObjectProxy @uses Ember.PromiseProxyMixin */ PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin); function promiseObject(promise, label) { return PromiseObject.create({ promise: Promise.cast(promise, label) }); } function promiseArray(promise, label) { return PromiseArray.create({ promise: Promise.cast(promise, label) }); } function isThenable(object) { return object && typeof object.then === 'function'; } function serializerFor(container, type, defaultSerializer) { return container.lookup('serializer:'+type) || container.lookup('serializer:application') || container.lookup('serializer:' + defaultSerializer) || container.lookup('serializer:-default'); } function defaultSerializer(container) { return container.lookup('serializer:application') || container.lookup('serializer:-default'); } function serializerForAdapter(adapter, type) { var serializer = adapter.serializer, defaultSerializer = adapter.defaultSerializer, container = adapter.container; if (container && serializer === undefined) { serializer = serializerFor(container, type.typeKey, defaultSerializer); } if (serializer === null || serializer === undefined) { serializer = { extract: function(store, type, payload) { return payload; } }; } return serializer; } function _find(adapter, store, type, id) { var promise = adapter.find(store, type, id), serializer = serializerForAdapter(adapter, type), label = "DS: Handle Adapter#find of " + type + " with id: " + id; return Promise.cast(promise, label).then(function(adapterPayload) { var payload = serializer.extract(store, type, adapterPayload, id, 'find'); return store.push(type, payload); }, function(error) { var record = store.getById(type, id); record.notFound(); throw error; }, "DS: Extract payload of '" + type + "'"); } function _findMany(adapter, store, type, ids, owner) { var promise = adapter.findMany(store, type, ids, owner), serializer = serializerForAdapter(adapter, type), label = "DS: Handle Adapter#findMany of " + type; return Promise.cast(promise, label).then(function(adapterPayload) { var payload = serializer.extract(store, type, adapterPayload, null, 'findMany'); store.pushMany(type, payload); }, null, "DS: Extract payload of " + type); } function _findHasMany(adapter, store, record, link, relationship) { var promise = adapter.findHasMany(store, record, link, relationship), serializer = serializerForAdapter(adapter, relationship.type), label = "DS: Handle Adapter#findHasMany of " + record + " : " + relationship.type; return Promise.cast(promise, label).then(function(adapterPayload) { var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findHasMany'); var records = store.pushMany(relationship.type, payload); record.updateHasMany(relationship.key, records); }, null, "DS: Extract payload of " + record + " : hasMany " + relationship.type); } function _findBelongsTo(adapter, store, record, link, relationship) { var promise = adapter.findBelongsTo(store, record, link, relationship), serializer = serializerForAdapter(adapter, relationship.type), label = "DS: Handle Adapter#findBelongsTo of " + record + " : " + relationship.type; return Promise.cast(promise, label).then(function(adapterPayload) { var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findBelongsTo'); var record = store.push(relationship.type, payload); record.updateBelongsTo(relationship.key, record); return record; }, null, "DS: Extract payload of " + record + " : " + relationship.type); } function _findAll(adapter, store, type, sinceToken) { var promise = adapter.findAll(store, type, sinceToken), serializer = serializerForAdapter(adapter, type), label = "DS: Handle Adapter#findAll of " + type; return Promise.cast(promise, label).then(function(adapterPayload) { var payload = serializer.extract(store, type, adapterPayload, null, 'findAll'); store.pushMany(type, payload); store.didUpdateAll(type); return store.all(type); }, null, "DS: Extract payload of findAll " + type); } function _findQuery(adapter, store, type, query, recordArray) { var promise = adapter.findQuery(store, type, query, recordArray), serializer = serializerForAdapter(adapter, type), label = "DS: Handle Adapter#findQuery of " + type; return Promise.cast(promise, label).then(function(adapterPayload) { var payload = serializer.extract(store, type, adapterPayload, null, 'findQuery'); recordArray.load(payload); return recordArray; }, null, "DS: Extract payload of findQuery " + type); } function _commit(adapter, store, operation, record) { var type = record.constructor, promise = adapter[operation](store, type, record), serializer = serializerForAdapter(adapter, type), label = "DS: Extract and notify about " + operation + " completion of " + record; return promise.then(function(adapterPayload) { var payload; if (adapterPayload) { payload = serializer.extract(store, type, adapterPayload, get(record, 'id'), operation); } else { payload = adapterPayload; } store.didSaveRecord(record, payload); return record; }, function(reason) { if (reason instanceof InvalidError) { store.recordWasInvalid(record, reason.errors); } else { store.recordWasError(record, reason); } throw reason; }, label); } __exports__.Store = Store; __exports__.PromiseArray = PromiseArray; __exports__.PromiseObject = PromiseObject; __exports__["default"] = Store; }); define("ember-data/lib/transforms", ["./transforms/base","./transforms/number","./transforms/date","./transforms/string","./transforms/boolean","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { "use strict"; var Transform = __dependency1__["default"]; var NumberTransform = __dependency2__["default"]; var DateTransform = __dependency3__["default"]; var StringTransform = __dependency4__["default"]; var BooleanTransform = __dependency5__["default"]; __exports__.Transform = Transform; __exports__.NumberTransform = NumberTransform; __exports__.DateTransform = DateTransform; __exports__.StringTransform = StringTransform; __exports__.BooleanTransform = BooleanTransform; }); define("ember-data/lib/transforms/base", ["exports"], function(__exports__) { "use strict"; /** The `DS.Transform` class is used to serialize and deserialize model attributes when they are saved or loaded from an adapter. Subclassing `DS.Transform` is useful for creating custom attributes. All subclasses of `DS.Transform` must implement a `serialize` and a `deserialize` method. Example ```javascript // Converts centigrade in the JSON to fahrenheit in the app App.TemperatureTransform = DS.Transform.extend({ deserialize: function(serialized) { return (serialized * 1.8) + 32; }, serialize: function(deserialized) { return (deserialized - 32) / 1.8; } }); ``` Usage ```javascript var attr = DS.attr; App.Requirement = DS.Model.extend({ name: attr('string'), optionsArray: attr('raw') }); ``` @class Transform @namespace DS */ var Transform = Ember.Object.extend({ /** When given a deserialized value from a record attribute this method must return the serialized value. Example ```javascript serialize: function(deserialized) { return Ember.isEmpty(deserialized) ? null : Number(deserialized); } ``` @method serialize @param deserialized The deserialized value @return The serialized value */ serialize: Ember.required(), /** When given a serialize value from a JSON object this method must return the deserialized value for the record attribute. Example ```javascript deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); } ``` @method deserialize @param serialized The serialized value @return The deserialized value */ deserialize: Ember.required() }); __exports__["default"] = Transform; }); define("ember-data/lib/transforms/boolean", ["./base","exports"], function(__dependency1__, __exports__) { "use strict"; var Transform = __dependency1__["default"]; /** The `DS.BooleanTransform` class is used to serialize and deserialize boolean attributes on Ember Data record objects. This transform is used when `boolean` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.User = DS.Model.extend({ isAdmin: attr('boolean'), name: attr('string'), email: attr('string') }); ``` @class BooleanTransform @extends DS.Transform @namespace DS */ var BooleanTransform = Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "boolean") { return serialized; } else if (type === "string") { return serialized.match(/^true$|^t$|^1$/i) !== null; } else if (type === "number") { return serialized === 1; } else { return false; } }, serialize: function(deserialized) { return Boolean(deserialized); } }); __exports__["default"] = BooleanTransform; }); define("ember-data/lib/transforms/date", ["./base","exports"], function(__dependency1__, __exports__) { "use strict"; /** The `DS.DateTransform` class is used to serialize and deserialize date attributes on Ember Data record objects. This transform is used when `date` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. ```javascript var attr = DS.attr; App.Score = DS.Model.extend({ value: attr('number'), player: DS.belongsTo('player'), date: attr('date') }); ``` @class DateTransform @extends DS.Transform @namespace DS */ var Transform = __dependency1__["default"]; var DateTransform = Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "string") { return new Date(Ember.Date.parse(serialized)); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is not present in the data, // return undefined, not null. return serialized; } else { return null; } }, serialize: function(date) { if (date instanceof Date) { var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var pad = function(num) { return num < 10 ? "0"+num : ""+num; }; var utcYear = date.getUTCFullYear(), utcMonth = date.getUTCMonth(), utcDayOfMonth = date.getUTCDate(), utcDay = date.getUTCDay(), utcHours = date.getUTCHours(), utcMinutes = date.getUTCMinutes(), utcSeconds = date.getUTCSeconds(); var dayOfWeek = days[utcDay]; var dayOfMonth = pad(utcDayOfMonth); var month = months[utcMonth]; return dayOfWeek + ", " + dayOfMonth + " " + month + " " + utcYear + " " + pad(utcHours) + ":" + pad(utcMinutes) + ":" + pad(utcSeconds) + " GMT"; } else { return null; } } }); __exports__["default"] = DateTransform; }); define("ember-data/lib/transforms/number", ["./base","exports"], function(__dependency1__, __exports__) { "use strict"; var Transform = __dependency1__["default"]; var empty = Ember.isEmpty; /** The `DS.NumberTransform` class is used to serialize and deserialize numeric attributes on Ember Data record objects. This transform is used when `number` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.Score = DS.Model.extend({ value: attr('number'), player: DS.belongsTo('player'), date: attr('date') }); ``` @class NumberTransform @extends DS.Transform @namespace DS */ var NumberTransform = Transform.extend({ deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); }, serialize: function(deserialized) { return empty(deserialized) ? null : Number(deserialized); } }); __exports__["default"] = NumberTransform; }); define("ember-data/lib/transforms/string", ["./base","exports"], function(__dependency1__, __exports__) { "use strict"; var Transform = __dependency1__["default"]; var none = Ember.isNone; /** The `DS.StringTransform` class is used to serialize and deserialize string attributes on Ember Data record objects. This transform is used when `string` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.User = DS.Model.extend({ isAdmin: attr('boolean'), name: attr('string'), email: attr('string') }); ``` @class StringTransform @extends DS.Transform @namespace DS */ var StringTransform = Transform.extend({ deserialize: function(serialized) { return none(serialized) ? null : String(serialized); }, serialize: function(deserialized) { return none(deserialized) ? null : String(deserialized); } }); __exports__["default"] = StringTransform; }); define("ember-inflector/lib/ext/string", ["../system/string"], function(__dependency1__) { "use strict"; var pluralize = __dependency1__.pluralize; var singularize = __dependency1__.singularize; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} @method pluralize @for String */ String.prototype.pluralize = function() { return pluralize(this); }; /** See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} @method singularize @for String */ String.prototype.singularize = function() { return singularize(this); }; } }); define("ember-inflector/lib/main", ["./system","./ext/string","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var Inflector = __dependency1__.Inflector; var defaultRules = __dependency1__.defaultRules; var pluralize = __dependency1__.pluralize; var singularize = __dependency1__.singularize; Inflector.defaultRules = defaultRules; Ember.Inflector = Inflector; Ember.String.pluralize = pluralize; Ember.String.singularize = singularize; __exports__["default"] = Inflector; __exports__.pluralize = pluralize; __exports__.singularize = singularize; }); define("ember-inflector/lib/system", ["./system/inflector","./system/string","./system/inflections","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var Inflector = __dependency1__["default"]; var pluralize = __dependency2__.pluralize; var singularize = __dependency2__.singularize; var defaultRules = __dependency3__["default"]; Inflector.inflector = new Inflector(defaultRules); __exports__.Inflector = Inflector; __exports__.singularize = singularize; __exports__.pluralize = pluralize; __exports__.defaultRules = defaultRules; }); define("ember-inflector/lib/system/inflections", ["exports"], function(__exports__) { "use strict"; var defaultRules = { plurals: [ [/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes'] ], singular: [ [/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1'] ], irregularPairs: [ ['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies'] ], uncountable: [ 'equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police' ] }; __exports__["default"] = defaultRules; }); define("ember-inflector/lib/system/inflector", ["exports"], function(__exports__) { "use strict"; var BLANK_REGEX = /^\s*$/; function loadUncountable(rules, uncountable) { for (var i = 0, length = uncountable.length; i < length; i++) { rules.uncountable[uncountable[i].toLowerCase()] = true; } } function loadIrregular(rules, irregularPairs) { var pair; for (var i = 0, length = irregularPairs.length; i < length; i++) { pair = irregularPairs[i]; rules.irregular[pair[0].toLowerCase()] = pair[1]; rules.irregularInverse[pair[1].toLowerCase()] = pair[0]; } } /** Inflector.Ember provides a mechanism for supplying inflection rules for your application. Ember includes a default set of inflection rules, and provides an API for providing additional rules. Examples: Creating an inflector with no rules. ```js var inflector = new Ember.Inflector(); ``` Creating an inflector with the default ember ruleset. ```js var inflector = new Ember.Inflector(Ember.Inflector.defaultRules); inflector.pluralize('cow'); //=> 'kine' inflector.singularize('kine'); //=> 'cow' ``` Creating an inflector and adding rules later. ```javascript var inflector = Ember.Inflector.inflector; inflector.pluralize('advice'); // => 'advices' inflector.uncountable('advice'); inflector.pluralize('advice'); // => 'advice' inflector.pluralize('formula'); // => 'formulas' inflector.irregular('formula', 'formulae'); inflector.pluralize('formula'); // => 'formulae' // you would not need to add these as they are the default rules inflector.plural(/$/, 's'); inflector.singular(/s$/i, ''); ``` Creating an inflector with a nondefault ruleset. ```javascript var rules = { plurals: [ /$/, 's' ], singular: [ /\s$/, '' ], irregularPairs: [ [ 'cow', 'kine' ] ], uncountable: [ 'fish' ] }; var inflector = new Ember.Inflector(rules); ``` @class Inflector @namespace Ember */ function Inflector(ruleSet) { ruleSet = ruleSet || {}; ruleSet.uncountable = ruleSet.uncountable || {}; ruleSet.irregularPairs = ruleSet.irregularPairs || {}; var rules = this.rules = { plurals: ruleSet.plurals || [], singular: ruleSet.singular || [], irregular: {}, irregularInverse: {}, uncountable: {} }; loadUncountable(rules, ruleSet.uncountable); loadIrregular(rules, ruleSet.irregularPairs); } Inflector.prototype = { /** @method plural @param {RegExp} regex @param {String} string */ plural: function(regex, string) { this.rules.plurals.push([regex, string.toLowerCase()]); }, /** @method singular @param {RegExp} regex @param {String} string */ singular: function(regex, string) { this.rules.singular.push([regex, string.toLowerCase()]); }, /** @method uncountable @param {String} regex */ uncountable: function(string) { loadUncountable(this.rules, [string.toLowerCase()]); }, /** @method irregular @param {String} singular @param {String} plural */ irregular: function (singular, plural) { loadIrregular(this.rules, [[singular, plural]]); }, /** @method pluralize @param {String} word */ pluralize: function(word) { return this.inflect(word, this.rules.plurals, this.rules.irregular); }, /** @method singularize @param {String} word */ singularize: function(word) { return this.inflect(word, this.rules.singular, this.rules.irregularInverse); }, /** @protected @method inflect @param {String} word @param {Object} typeRules @param {Object} irregular */ inflect: function(word, typeRules, irregular) { var inflection, substitution, result, lowercase, isBlank, isUncountable, isIrregular, isIrregularInverse, rule; isBlank = BLANK_REGEX.test(word); if (isBlank) { return word; } lowercase = word.toLowerCase(); isUncountable = this.rules.uncountable[lowercase]; if (isUncountable) { return word; } isIrregular = irregular && irregular[lowercase]; if (isIrregular) { return isIrregular; } for (var i = typeRules.length, min = 0; i > min; i--) { inflection = typeRules[i-1]; rule = inflection[0]; if (rule.test(word)) { break; } } inflection = inflection || []; rule = inflection[0]; substitution = inflection[1]; result = word.replace(rule, substitution); return result; } }; __exports__["default"] = Inflector; }); define("ember-inflector/lib/system/string", ["./inflector","exports"], function(__dependency1__, __exports__) { "use strict"; var Inflector = __dependency1__["default"]; var pluralize = function(word) { return Inflector.inflector.pluralize(word); }; var singularize = function(word) { return Inflector.inflector.singularize(word); }; __exports__.pluralize = pluralize; __exports__.singularize = singularize; }); global.DS = requireModule('ember-data/lib/main')['default']; }(Ember.lookup));
src/components/d3componentsv2/Point.js
nbuechler/ample-affect-exhibit
import React from 'react'; import ReactDOM from 'react-dom'; import d3 from 'd3'; import _ from 'underscore'; export default class Point extends React.Component { constructor (props) { super(props); this.state = { }; } render () { return ( <circle className={this.props.className} r={this.props.r} opacity={this.props.opacity} cx={(this.props.rangeBandTarget * this.props.rangeBand) + this.props.rangeBand/2 + '%'} cy={this.props.availableHeight - this.props.cy} stroke={this.props.stroke} style={{strokeWidth: '1px'}} /> ); } }
src/app/components/source/UserComponent.js
meedan/check-web
import React from 'react'; import PropTypes from 'prop-types'; import { browserHistory } from 'react-router'; import { FormattedMessage } from 'react-intl'; import Box from '@material-ui/core/Box'; import Tabs from '@material-ui/core/Tabs'; import Tab from '@material-ui/core/Tab'; import UserEmail from '../user/UserEmail'; import UserInfo from './UserInfo'; import UserAssignments from './UserAssignments'; import UserPrivacy from './UserPrivacy'; import UserSecurity from './UserSecurity'; import UserInfoEdit from './UserInfoEdit'; import { can } from '../Can'; import PageTitle from '../PageTitle'; import CheckContext from '../../CheckContext'; import SwitchTeamsComponent from '../team/SwitchTeamsComponent'; import { ContentColumn } from '../../styles/js/shared'; class UserComponent extends React.Component { constructor(props) { super(props); const { tab } = this.props.params; const showTab = (typeof tab === 'undefined') ? 'assignments' : tab; this.state = { showTab, }; } componentWillMount() { const { user } = this.props; if (!user.is_active) { browserHistory.push('/check/not-found'); } } getContext() { return new CheckContext(this).getContextStore(); } handleTabChange = (e, value) => { browserHistory.push(`/check/user/${this.props.user.dbid}/${value}`); this.setState({ showTab: value, }); }; render() { const { user } = this.props; const isEditing = this.props.route.isEditing && can(user.permissions, 'update User'); const context = this.getContext(); const isUserSelf = (user.id === context.currentUser.id); const HeaderContent = () => ( <Box pt={3} pb={3}> { isEditing ? <UserInfoEdit user={user} /> : <UserInfo user={user} context={context} /> } </Box> ); return ( <PageTitle prefix={user.name}> <div className="source"> <ContentColumn> <HeaderContent /> { isEditing ? null : ( <Tabs indicatorColor="primary" textColor="primary" value={this.state.showTab} onChange={this.handleTabChange} > <Tab id="teams-tab" label={ <FormattedMessage id="userComponent.teams" defaultMessage="Workspaces" /> } value="workspaces" /> <Tab id="assignments-tab" label={ <FormattedMessage id="userComponents.assignments" defaultMessage="Assignments" /> } value="assignments" /> { isUserSelf ? <Tab id="privacy-tab" label={ <FormattedMessage id="userComponents.privacy" defaultMessage="Privacy" /> } value="privacy" /> : null } { isUserSelf ? <Tab id="security-tab" label={ <FormattedMessage id="userComponents.security" defaultMessage="Security" /> } value="security" /> : null } </Tabs> ) } </ContentColumn> <ContentColumn> { isEditing ? null : <div> <UserEmail user={user} /> { this.state.showTab === 'teams' || this.state.showTab === 'workspaces' ? <SwitchTeamsComponent user={user} /> : null} { this.state.showTab === 'assignments' ? <UserAssignments user={user} /> : null} { this.state.showTab === 'privacy' ? <UserPrivacy user={user} /> : null} { this.state.showTab === 'security' ? <UserSecurity user={user} /> : null} </div> } </ContentColumn> </div> </PageTitle> ); } } UserComponent.contextTypes = { store: PropTypes.object, }; export default UserComponent;
src/containers/edm/components/ActionDropdown.js
dataloom/gallery
import React from 'react'; import Immutable from 'immutable'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { SplitButton, MenuItem } from 'react-bootstrap'; import { connect } from 'react-redux'; import { Link, hashHistory } from 'react-router'; import { bindActionCreators } from 'redux'; import DropdownSearchBox from '../../../containers/entitysetsearch/DropdownSearchBox'; import PageConsts from '../../../utils/Consts/PageConsts'; import * as PermissionsActionFactory from '../../permissions/PermissionsActionFactory'; import { createAsyncComponent } from '../../async/components/AsyncContentComponent'; import { createAuthnAsyncReference, createAccessCheck } from '../../permissions/PermissionsStorage'; import { createEntityTypeAsyncReference } from '../EdmAsyncStorage'; import { EntityTypePropType } from '../EdmModel'; class ActionDropdown extends React.Component { static propTypes = { entitySetId: PropTypes.string.isRequired, // propertyTypeAuthorizations: PropTypes.arrayOf(AuthorizationPropType).isRequired, propertyTypeAuthorizations: PropTypes.array.isRequired, showDetails: PropTypes.bool, className: PropTypes.string, onRequestPermissions: PropTypes.func.isRequired }; static defaultProps = { showDetails: false, className: null }; canRequestPermissions() { const { propertyTypeAuthorizations } = this.props; return !propertyTypeAuthorizations.every((authorization) => { return authorization.permissions.READ; }); } renderRequestPermissions() { const { entitySetId, onRequestPermissions } = this.props; if (this.canRequestPermissions()) { return ( <MenuItem onSelect={() => { onRequestPermissions(entitySetId); }}> Request Permissions </MenuItem> ); } return null; } renderViewDetails() { if (this.props.showDetails) { return ( <li role="presentation"> <Link to={`/entitysets/${this.props.entitySetId}`}> View Details </Link> </li> ); } return null; } goToViewDetails = () => { if (this.props.showDetails) { hashHistory.push(`/entitysets/${this.props.entitySetId}`); } }; render() { const { entitySetId } = this.props; const title = (!this.props.showDetails) ? 'Actions' : 'View Details'; return ( <SplitButton pullRight title={title} bsStyle="primary" id="action-dropdown" className={classnames(this.props.className)} onClick={this.goToViewDetails}> { this.renderViewDetails() } { this.renderRequestPermissions() } <MenuItem divider /> <li role="presentation"> <Link to={{ pathname: `/${PageConsts.ENTITY_SETS}/${this.props.entitySetId}/toputilizers` }}> Find Top Utilizers </Link> </li> <MenuItem divider /> <DropdownSearchBox entitySetId={entitySetId} /> </SplitButton>); } } ActionDropdown.Async = createAsyncComponent(ActionDropdown); class ActionDropdownWrapper extends React.Component { static propTypes = { entitySetId: PropTypes.string.isRequired, entityType: EntityTypePropType.isRequired, loadPropertyTypePermissions: PropTypes.func.isRequired }; componentDidMount() { // TODO - this can be improved. when there's multiple of these on the page, a new request will be fired off // to load permissions. there should be a way to combine all of these requests into a single request (perhaps with // rxjs Observables) const { loadPropertyTypePermissions } = this.props; loadPropertyTypePermissions(this.getAclKeys()); } getAclKeys() { const { entityType, entitySetId } = this.props; return entityType.properties.map((propertyTypeId) => { return [entitySetId, propertyTypeId]; }); } render() { const propertyTypeAuthorizationReferences = this.getAclKeys().map(createAuthnAsyncReference); return ( <ActionDropdown.Async propertyTypeAuthorizations={propertyTypeAuthorizationReferences} {...this.props} />); } } ActionDropdownWrapper.Async = createAsyncComponent(ActionDropdownWrapper); function mapStateToProps(state, ownProps) { const { entitySetId } = ownProps; const entitySet = state.getIn(['edm', 'entitySets', entitySetId], Immutable.Map()); let entityTypeAsyncReference; if (!entitySet.isEmpty()) { entityTypeAsyncReference = createEntityTypeAsyncReference(entitySet.get('entityTypeId')); } else { // TODO: replace with actual empty reference in async/ entityTypeAsyncReference = createEntityTypeAsyncReference(''); } return { entityType: entityTypeAsyncReference }; } // TODO: Decide if/how to incorporate bindActionCreators function mapDispatchToProps(dispatch) { return bindActionCreators({ onRequestPermissions: PermissionsActionFactory.requestPermissionsModalShow, loadPropertyTypePermissions: (aclKeys) => { const accessChecks = aclKeys.map(createAccessCheck); return PermissionsActionFactory.checkAuthorizationRequest(accessChecks); } }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(ActionDropdownWrapper.Async);
src/index.js
NJU-itxia/front-end
import 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap/dist/css/bootstrap-theme.min.css'; import 'bootstrap/dist/js/bootstrap.min.js'; import React from 'react'; import ReactDOM from 'react-dom'; import { browserHistory, Router, Route, IndexRedirect, Redirect, Link, IndexLink } from 'react-router'; import App from './App'; import LoginPage from './component/login/LoginPage'; import StudentLogin from './component/login/StudentLogin'; import KnightLogin from './component/login/KnightLogin'; import StudentPage from './component/student/StudentPage'; import NewOrder from './component/student/NewOrder'; import History from './component/student/History'; import KnightPage from './component/knight/KnightPage'; import Orders from './component/knight/order/Orders'; import Message from './component/knight/Message'; import Setting from './component/knight/Setting'; import studentModel from './model/student'; import knightModel from './model/knight'; function redirectIfLoggedIn(nextState, replace) { if (studentModel.token) { replace('/student/order'); } else if (knightModel.token) { // TODO } } function requireStudentLogin(nextState, replace) { if (!studentModel.token) { replace('/'); } } function requireKnightLogin() { if (!knightModel.token) { replace('/'); } } const routes = ( <Router history={browserHistory}> <Route path="/" component={App}> <IndexRedirect to="/login/student" /> <Route path="login" component={LoginPage} onEnter={redirectIfLoggedIn} > <Route path="student" component={StudentLogin} /> <Route path="knight" component={KnightLogin} /> </Route> <Route path="student" component={StudentPage} onEnter={requireStudentLogin} > <Route path="order" component={NewOrder} /> <Route path="history" component={History} /> </Route> <Route path="knight" component={KnightPage} onEnter={requireKnightLogin} > <Route path="orders" component={ Orders } /> <Route path="message" component={Message} /> <Route path="setting" component={Setting} /> </Route> </Route> </Router> ); function renderAll() { console.log('render'); ReactDOM.render(routes, document.getElementById('app')); } studentModel.subscribe(renderAll); renderAll();
__site/magiastormenta/node_modules/core-js/modules/es6.promise.js
RoenMidnight/grimorio-trpg
'use strict'; var LIBRARY = require('./_library'); var global = require('./_global'); var ctx = require('./_ctx'); var classof = require('./_classof'); var $export = require('./_export'); var isObject = require('./_is-object'); var aFunction = require('./_a-function'); var anInstance = require('./_an-instance'); var forOf = require('./_for-of'); var speciesConstructor = require('./_species-constructor'); var task = require('./_task').set; var microtask = require('./_microtask')(); var newPromiseCapabilityModule = require('./_new-promise-capability'); var perform = require('./_perform'); var promiseResolve = require('./_promise-resolve'); var PROMISE = 'Promise'; var TypeError = global.TypeError; var process = global.process; var $Promise = global[PROMISE]; var isNode = classof(process) == 'process'; var empty = function () { /* empty */ }; var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; var USE_NATIVE = !!function () { try { // correct subclassing with @@species support var promise = $Promise.resolve(1); var FakePromise = (promise.constructor = {})[require('./_wks')('species')] = function (exec) { exec(empty, empty); }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; } catch (e) { /* empty */ } }(); // helpers var isThenable = function (it) { var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var notify = function (promise, isReject) { if (promise._n) return; promise._n = true; var chain = promise._c; microtask(function () { var value = promise._v; var ok = promise._s == 1; var i = 0; var run = function (reaction) { var handler = ok ? reaction.ok : reaction.fail; var resolve = reaction.resolve; var reject = reaction.reject; var domain = reaction.domain; var result, then; try { if (handler) { if (!ok) { if (promise._h == 2) onHandleUnhandled(promise); promise._h = 1; } if (handler === true) result = value; else { if (domain) domain.enter(); result = handler(value); if (domain) domain.exit(); } if (result === reaction.promise) { reject(TypeError('Promise-chain cycle')); } else if (then = isThenable(result)) { then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch (e) { reject(e); } }; while (chain.length > i) run(chain[i++]); // variable length - can't use forEach promise._c = []; promise._n = false; if (isReject && !promise._h) onUnhandled(promise); }); }; var onUnhandled = function (promise) { task.call(global, function () { var value = promise._v; var unhandled = isUnhandled(promise); var result, handler, console; if (unhandled) { result = perform(function () { if (isNode) { process.emit('unhandledRejection', value, promise); } else if (handler = global.onunhandledrejection) { handler({ promise: promise, reason: value }); } else if ((console = global.console) && console.error) { console.error('Unhandled promise rejection', value); } }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if (unhandled && result.e) throw result.v; }); }; var isUnhandled = function (promise) { return promise._h !== 1 && (promise._a || promise._c).length === 0; }; var onHandleUnhandled = function (promise) { task.call(global, function () { var handler; if (isNode) { process.emit('rejectionHandled', promise); } else if (handler = global.onrejectionhandled) { handler({ promise: promise, reason: promise._v }); } }); }; var $reject = function (value) { var promise = this; if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap promise._v = value; promise._s = 2; if (!promise._a) promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function (value) { var promise = this; var then; if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap try { if (promise === value) throw TypeError("Promise can't be resolved itself"); if (then = isThenable(value)) { microtask(function () { var wrapper = { _w: promise, _d: false }; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch (e) { $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch (e) { $reject.call({ _w: promise, _d: false }, e); // wrap } }; // constructor polyfill if (!USE_NATIVE) { // 25.4.3.1 Promise(executor) $Promise = function Promise(executor) { anInstance(this, $Promise, PROMISE, '_h'); aFunction(executor); Internal.call(this); try { executor(ctx($resolve, this, 1), ctx($reject, this, 1)); } catch (err) { $reject.call(this, err); } }; // eslint-disable-next-line no-unused-vars Internal = function Promise(executor) { this._c = []; // <- awaiting reactions this._a = undefined; // <- checked in isUnhandled reactions this._s = 0; // <- state this._d = false; // <- done this._v = undefined; // <- value this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; Internal.prototype = require('./_redefine-all')($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected) { var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if (this._a) this._a.push(reaction); if (this._s) notify(this, false); return reaction.promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function (onRejected) { return this.then(undefined, onRejected); } }); OwnPromiseCapability = function () { var promise = new Internal(); this.promise = promise; this.resolve = ctx($resolve, promise, 1); this.reject = ctx($reject, promise, 1); }; newPromiseCapabilityModule.f = newPromiseCapability = function (C) { return C === $Promise || C === Wrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); require('./_set-to-string-tag')($Promise, PROMISE); require('./_set-species')(PROMISE); Wrapper = require('./_core')[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r) { var capability = newPromiseCapability(this); var $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x) { return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); } }); $export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(function (iter) { $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable) { var C = this; var capability = newPromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; var result = perform(function () { var values = []; var index = 0; var remaining = 1; forOf(iterable, false, function (promise) { var $index = index++; var alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function (value) { if (alreadyCalled) return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if (result.e) reject(result.v); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable) { var C = this; var capability = newPromiseCapability(C); var reject = capability.reject; var result = perform(function () { forOf(iterable, false, function (promise) { C.resolve(promise).then(capability.resolve, reject); }); }); if (result.e) reject(result.v); return capability.promise; } });
src/svg-icons/action/class.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionClass = (props) => ( <SvgIcon {...props}> <path d="M18 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 4h5v8l-2.5-1.5L6 12V4z"/> </SvgIcon> ); ActionClass = pure(ActionClass); ActionClass.displayName = 'ActionClass'; ActionClass.muiName = 'SvgIcon'; export default ActionClass;
test/e2e/getserversideprops/app/pages/something.js
azukaru/next.js
import React from 'react' import Link from 'next/link' import { useRouter } from 'next/router' export async function getServerSideProps({ params, query, resolvedUrl }) { return { props: { resolvedUrl: resolvedUrl, world: 'world', query: query || {}, params: params || {}, time: new Date().getTime(), random: Math.random(), }, } } export default ({ world, time, params, random, query, appProps, resolvedUrl, }) => { const router = useRouter() return ( <> <p>hello: {world}</p> <span>time: {time}</span> <div id="random">{random}</div> <div id="params">{JSON.stringify(params)}</div> <div id="initial-query">{JSON.stringify(query)}</div> <div id="query">{JSON.stringify(router.query)}</div> <div id="app-query">{JSON.stringify(appProps.query)}</div> <div id="app-url">{appProps.url}</div> <div id="resolved-url">{resolvedUrl}</div> <div id="as-path">{router.asPath}</div> <Link href="/"> <a id="home">to home</a> </Link> <br /> <Link href="/another"> <a id="another">to another</a> </Link> </> ) }
ajax/libs/angular-google-maps/1.0.9/angular-google-maps.js
ramda/cdnjs
/* Author Nick McCready Intersection of Objects if the arrays have something in common each intersecting object will be returned in an new array. */ (function() { _.intersectionObjects = function(array1, array2, comparison) { var res, _this = this; if (comparison == null) { comparison = void 0; } res = _.map(array1, function(obj1) { return _.find(array2, function(obj2) { if (comparison != null) { return comparison(obj1, obj2); } else { return _.isEqual(obj1, obj2); } }); }); return _.filter(res, function(o) { return o != null; }); }; }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { (function() { var app; app = angular.module("google-maps", []); return app.factory("debounce", [ "$timeout", function($timeout) { return function(fn) { var nthCall; nthCall = 0; return function() { var argz, later, that; that = this; argz = arguments; nthCall++; later = (function(version) { return function() { if (version === nthCall) { return fn.apply(that, argz); } }; })(nthCall); return $timeout(later, 0, true); }; }; } ]); })(); }).call(this); (function() { this.ngGmapModule = function(names, fn) { var space, _name; if (fn == null) { fn = function() {}; } if (typeof names === 'string') { names = names.split('.'); } space = this[_name = names.shift()] || (this[_name] = {}); space.ngGmapModule || (space.ngGmapModule = this.ngGmapModule); if (names.length) { return space.ngGmapModule(names, fn); } else { return fn.call(space); } }; }).call(this); (function() { angular.module("google-maps").factory("array-sync", [ "add-events", function(mapEvents) { var LatLngArraySync; return LatLngArraySync = function(mapArray, scope, pathEval) { var mapArrayListener, scopeArray, watchListener; scopeArray = scope.$eval(pathEval); mapArrayListener = mapEvents(mapArray, { set_at: function(index) { var value; value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } scopeArray[index].latitude = value.lat(); return scopeArray[index].longitude = value.lng(); }, insert_at: function(index) { var value; value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } return scopeArray.splice(index, 0, { latitude: value.lat(), longitude: value.lng() }); }, remove_at: function(index) { return scopeArray.splice(index, 1); } }); watchListener = scope.$watch(pathEval, function(newArray) { var i, l, newLength, newValue, oldArray, oldLength, oldValue, _results; oldArray = mapArray; if (newArray) { i = 0; oldLength = oldArray.getLength(); newLength = newArray.length; l = Math.min(oldLength, newLength); newValue = void 0; while (i < l) { oldValue = oldArray.getAt(i); newValue = newArray[i]; if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) { oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude)); } i++; } while (i < newLength) { newValue = newArray[i]; oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude)); i++; } _results = []; while (i < oldLength) { oldArray.pop(); _results.push(i++); } return _results; } }, true); return function() { if (mapArrayListener) { mapArrayListener(); mapArrayListener = null; } if (watchListener) { watchListener(); return watchListener = null; } }; }; } ]); }).call(this); (function() { angular.module("google-maps").factory("add-events", [ "$timeout", function($timeout) { var addEvent, addEvents; addEvent = function(target, eventName, handler) { return google.maps.event.addListener(target, eventName, function() { handler.apply(this, arguments); return $timeout((function() {}), true); }); }; addEvents = function(target, eventName, handler) { var remove; if (handler) { return addEvent(target, eventName, handler); } remove = []; angular.forEach(eventName, function(_handler, key) { return remove.push(addEvent(target, key, _handler)); }); return function() { angular.forEach(remove, function(fn) { if (_.isFunction(fn)) { fn(); } if (fn.e !== null && _.isFunction(fn.e)) { return fn.e(); } }); return remove = null; }; }; return addEvents; } ]); }).call(this); (function() { var __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; this.ngGmapModule("oo", function() { var baseObjectKeywords; baseObjectKeywords = ['extended', 'included']; return this.BaseObject = (function() { function BaseObject() {} BaseObject.extend = function(obj) { var key, value, _ref; for (key in obj) { value = obj[key]; if (__indexOf.call(baseObjectKeywords, key) < 0) { this[key] = value; } } if ((_ref = obj.extended) != null) { _ref.apply(0); } return this; }; BaseObject.include = function(obj) { var key, value, _ref; for (key in obj) { value = obj[key]; if (__indexOf.call(baseObjectKeywords, key) < 0) { this.prototype[key] = value; } } if ((_ref = obj.included) != null) { _ref.apply(0); } return this; }; return BaseObject; })(); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.managers", function() { return this.ClustererMarkerManager = (function(_super) { __extends(ClustererMarkerManager, _super); function ClustererMarkerManager(gMap, opt_markers, opt_options) { this.clear = __bind(this.clear, this); this.draw = __bind(this.draw, this); this.removeMany = __bind(this.removeMany, this); this.remove = __bind(this.remove, this); this.addMany = __bind(this.addMany, this); this.add = __bind(this.add, this); var self; ClustererMarkerManager.__super__.constructor.call(this); self = this; this.opt_options = opt_options; if ((opt_options != null) && opt_markers === void 0) { this.clusterer = new MarkerClusterer(gMap, void 0, opt_options); } else if ((opt_options != null) && (opt_markers != null)) { this.clusterer = new MarkerClusterer(gMap, opt_markers, opt_options); } else { this.clusterer = new MarkerClusterer(gMap); } this.clusterer.setIgnoreHidden(true); this.$log = directives.api.utils.Logger; this.noDrawOnSingleAddRemoves = true; this.$log.info(this); } ClustererMarkerManager.prototype.add = function(gMarker) { return this.clusterer.addMarker(gMarker, this.noDrawOnSingleAddRemoves); }; ClustererMarkerManager.prototype.addMany = function(gMarkers) { return this.clusterer.addMarkers(gMarkers); }; ClustererMarkerManager.prototype.remove = function(gMarker) { return this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves); }; ClustererMarkerManager.prototype.removeMany = function(gMarkers) { return this.clusterer.addMarkers(gMarkers); }; ClustererMarkerManager.prototype.draw = function() { return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.clear = function() { this.clusterer.clearMarkers(); return this.clusterer.repaint(); }; return ClustererMarkerManager; })(oo.BaseObject); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.managers", function() { return this.MarkerManager = (function(_super) { __extends(MarkerManager, _super); function MarkerManager(gMap, opt_markers, opt_options) { this.handleOptDraw = __bind(this.handleOptDraw, this); this.clear = __bind(this.clear, this); this.draw = __bind(this.draw, this); this.removeMany = __bind(this.removeMany, this); this.remove = __bind(this.remove, this); this.addMany = __bind(this.addMany, this); this.add = __bind(this.add, this); var self; MarkerManager.__super__.constructor.call(this); self = this; this.gMap = gMap; this.gMarkers = []; this.$log = directives.api.utils.Logger; this.$log.info(this); } MarkerManager.prototype.add = function(gMarker, optDraw) { this.handleOptDraw(gMarker, optDraw, true); return this.gMarkers.push(gMarker); }; MarkerManager.prototype.addMany = function(gMarkers) { var gMarker, _i, _len, _results; _results = []; for (_i = 0, _len = gMarkers.length; _i < _len; _i++) { gMarker = gMarkers[_i]; _results.push(this.add(gMarker)); } return _results; }; MarkerManager.prototype.remove = function(gMarker, optDraw) { var index, tempIndex; this.handleOptDraw(gMarker, optDraw, false); if (!optDraw) { return; } index = void 0; if (this.gMarkers.indexOf != null) { index = this.gMarkers.indexOf(gMarker); } else { tempIndex = 0; _.find(this.gMarkers, function(marker) { tempIndex += 1; if (marker === gMarker) { index = tempIndex; } }); } if (index != null) { return this.gMarkers.splice(index, 1); } }; MarkerManager.prototype.removeMany = function(gMarkers) { var marker, _i, _len, _ref, _results; _ref = this.gMarkers; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { marker = _ref[_i]; _results.push(this.remove(marker)); } return _results; }; MarkerManager.prototype.draw = function() { var deletes, gMarker, _fn, _i, _j, _len, _len1, _ref, _results, _this = this; deletes = []; _ref = this.gMarkers; _fn = function(gMarker) { if (!gMarker.isDrawn) { if (gMarker.doAdd) { return gMarker.setMap(_this.gMap); } else { return deletes.push(gMarker); } } }; for (_i = 0, _len = _ref.length; _i < _len; _i++) { gMarker = _ref[_i]; _fn(gMarker); } _results = []; for (_j = 0, _len1 = deletes.length; _j < _len1; _j++) { gMarker = deletes[_j]; _results.push(this.remove(gMarker, true)); } return _results; }; MarkerManager.prototype.clear = function() { var gMarker, _i, _len, _ref; _ref = this.gMarkers; for (_i = 0, _len = _ref.length; _i < _len; _i++) { gMarker = _ref[_i]; gMarker.setMap(null); } delete this.gMarkers; return this.gMarkers = []; }; MarkerManager.prototype.handleOptDraw = function(gMarker, optDraw, doAdd) { if (optDraw === true) { if (doAdd) { gMarker.setMap(this.gMap); } else { gMarker.setMap(null); } return gMarker.isDrawn = true; } else { gMarker.isDrawn = false; return gMarker.doAdd = doAdd; } }; return MarkerManager; })(oo.BaseObject); }); }).call(this); /* Author: Nicholas McCready & jfriend00 AsyncProcessor handles things asynchronous-like :), to allow the UI to be free'd to do other things Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui */ (function() { this.ngGmapModule("directives.api.utils", function() { return this.AsyncProcessor = { handleLargeArray: function(array, callback, pausedCallBack, doneCallBack, chunk, index) { var doChunk; if (chunk == null) { chunk = 100; } if (index == null) { index = 0; } if (array === void 0 || array.length <= 0) { doneCallBack(); return; } doChunk = function() { var cnt, i; cnt = chunk; i = index; while (cnt-- && i < array.length) { callback(array[i]); ++i; } if (i < array.length) { index = i; if (pausedCallBack != null) { pausedCallBack(); } return setTimeout(doChunk, 1); } else { return doneCallBack(); } }; return doChunk(); } }; }); }).call(this); /* Useful function callbacks that should be defined at later time. Mainly to be used for specs to verify creation / linking. This is to lead a common design in notifying child stuff. */ (function() { this.ngGmapModule("directives.api.utils", function() { return this.ChildEvents = { onChildCreation: function(child) {} }; }); }).call(this); (function() { this.ngGmapModule("directives.api.utils", function() { return this.GmapUtil = { getLabelPositionPoint: function(anchor) { var xPos, yPos; if (anchor === void 0) { return void 0; } anchor = /^([\d\.]+)\s([\d\.]+)$/.exec(anchor); xPos = anchor[1]; yPos = anchor[2]; if (xPos && yPos) { return new google.maps.Point(xPos, yPos); } }, createMarkerOptions: function(coords, icon, defaults, map) { var opts; if (map == null) { map = void 0; } if (defaults == null) { defaults = {}; } opts = angular.extend({}, defaults, { position: defaults.position != null ? defaults.position : new google.maps.LatLng(coords.latitude, coords.longitude), icon: defaults.icon != null ? defaults.icon : icon, visible: defaults.visible != null ? defaults.visible : (coords.latitude != null) && (coords.longitude != null) }); if (map != null) { opts.map = map; } return opts; }, createWindowOptions: function(gMarker, scope, content, defaults) { if ((content != null) && (defaults != null)) { return angular.extend({}, defaults, { content: defaults.content != null ? defaults.content : content, position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude) }); } }, defaultDelay: 50 }; }); }).call(this); (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.utils", function() { return this.Linked = (function(_super) { __extends(Linked, _super); function Linked(scope, element, attrs, ctrls) { this.scope = scope; this.element = element; this.attrs = attrs; this.ctrls = ctrls; } return Linked; })(oo.BaseObject); }); }).call(this); (function() { this.ngGmapModule("directives.api.utils", function() { var logger; this.Logger = { logger: void 0, doLog: false, info: function(msg) { if (logger.doLog) { if (logger.logger != null) { return logger.logger.info(msg); } else { return console.info(msg); } } }, error: function(msg) { if (logger.doLog) { if (logger.logger != null) { return logger.logger.error(msg); } else { return console.error(msg); } } } }; return logger = this.Logger; }); }).call(this); (function() { this.ngGmapModule("directives.api.utils", function() { return this.ModelsWatcher = { didModelsChange: function(newValue, oldValue) { var didModelsChange, hasIntersectionDiff; if (!_.isArray(newValue)) { directives.api.utils.Logger.error("models property must be an array newValue of: " + (newValue.toString()) + " is not!!"); return false; } if (newValue === oldValue) { return false; } hasIntersectionDiff = _.intersectionObjects(newValue, oldValue).length !== oldValue.length; didModelsChange = true; if (!hasIntersectionDiff) { didModelsChange = newValue.length !== oldValue.length; } return didModelsChange; } }; }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.child", function() { return this.MarkerLabelChildModel = (function(_super) { __extends(MarkerLabelChildModel, _super); MarkerLabelChildModel.include(directives.api.utils.GmapUtil); function MarkerLabelChildModel(gMarker, opt_options) { this.destroy = __bind(this.destroy, this); this.draw = __bind(this.draw, this); this.setPosition = __bind(this.setPosition, this); this.setZIndex = __bind(this.setZIndex, this); this.setVisible = __bind(this.setVisible, this); this.setAnchor = __bind(this.setAnchor, this); this.setMandatoryStyles = __bind(this.setMandatoryStyles, this); this.setStyles = __bind(this.setStyles, this); this.setContent = __bind(this.setContent, this); this.setTitle = __bind(this.setTitle, this); this.getSharedCross = __bind(this.getSharedCross, this); var self, _ref, _ref1; MarkerLabelChildModel.__super__.constructor.call(this); self = this; this.marker = gMarker; this.marker.set("labelContent", opt_options.labelContent); this.marker.set("labelAnchor", this.getLabelPositionPoint(opt_options.labelAnchor)); this.marker.set("labelClass", opt_options.labelClass || 'labels'); this.marker.set("labelStyle", opt_options.labelStyle || { opacity: 100 }); this.marker.set("labelInBackground", opt_options.labelInBackground || false); if (!opt_options.labelVisible) { this.marker.set("labelVisible", true); } if (!opt_options.raiseOnDrag) { this.marker.set("raiseOnDrag", true); } if (!opt_options.clickable) { this.marker.set("clickable", true); } if (!opt_options.draggable) { this.marker.set("draggable", false); } if (!opt_options.optimized) { this.marker.set("optimized", false); } opt_options.crossImage = (_ref = opt_options.crossImage) != null ? _ref : document.location.protocol + "//maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; opt_options.handCursor = (_ref1 = opt_options.handCursor) != null ? _ref1 : document.location.protocol + "//maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"; this.markerLabel = new MarkerLabel_(this.marker, opt_options.crossImage, opt_options.handCursor); this.marker.set("setMap", function(theMap) { google.maps.Marker.prototype.setMap.apply(this, arguments); return self.markerLabel.setMap(theMap); }); this.marker.setMap(this.marker.getMap()); } MarkerLabelChildModel.prototype.getSharedCross = function(crossUrl) { return this.markerLabel.getSharedCross(crossUrl); }; MarkerLabelChildModel.prototype.setTitle = function() { return this.markerLabel.setTitle(); }; MarkerLabelChildModel.prototype.setContent = function() { return this.markerLabel.setContent(); }; MarkerLabelChildModel.prototype.setStyles = function() { return this.markerLabel.setStyles(); }; MarkerLabelChildModel.prototype.setMandatoryStyles = function() { return this.markerLabel.setMandatoryStyles(); }; MarkerLabelChildModel.prototype.setAnchor = function() { return this.markerLabel.setAnchor(); }; MarkerLabelChildModel.prototype.setVisible = function() { return this.markerLabel.setVisible(); }; MarkerLabelChildModel.prototype.setZIndex = function() { return this.markerLabel.setZIndex(); }; MarkerLabelChildModel.prototype.setPosition = function() { return this.markerLabel.setPosition(); }; MarkerLabelChildModel.prototype.draw = function() { return this.markerLabel.draw(); }; MarkerLabelChildModel.prototype.destroy = function() { if ((this.markerLabel.labelDiv_.parentNode != null) && (this.markerLabel.eventDiv_.parentNode != null)) { return this.markerLabel.onRemove(); } }; return MarkerLabelChildModel; })(oo.BaseObject); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.child", function() { return this.MarkerChildModel = (function(_super) { __extends(MarkerChildModel, _super); MarkerChildModel.include(directives.api.utils.GmapUtil); function MarkerChildModel(index, model, parentScope, gMap, $timeout, defaults, doClick, gMarkerManager) { var self, _this = this; this.index = index; this.model = model; this.parentScope = parentScope; this.gMap = gMap; this.defaults = defaults; this.doClick = doClick; this.gMarkerManager = gMarkerManager; this.watchDestroy = __bind(this.watchDestroy, this); this.setLabelOptions = __bind(this.setLabelOptions, this); this.isLabelDefined = __bind(this.isLabelDefined, this); this.setOptions = __bind(this.setOptions, this); this.setIcon = __bind(this.setIcon, this); this.setCoords = __bind(this.setCoords, this); this.destroy = __bind(this.destroy, this); this.maybeSetScopeValue = __bind(this.maybeSetScopeValue, this); this.createMarker = __bind(this.createMarker, this); this.setMyScope = __bind(this.setMyScope, this); self = this; this.iconKey = this.parentScope.icon; this.coordsKey = this.parentScope.coords; this.clickKey = this.parentScope.click(); this.labelContentKey = this.parentScope.labelContent; this.optionsKey = this.parentScope.options; this.labelOptionsKey = this.parentScope.labelOptions; this.myScope = this.parentScope.$new(false); this.myScope.model = this.model; this.setMyScope(this.model, void 0, true); this.createMarker(this.model); this.myScope.$watch('model', function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setMyScope(newValue, oldValue); } }, true); this.$log = directives.api.utils.Logger; this.$log.info(self); this.watchDestroy(this.myScope); } MarkerChildModel.prototype.setMyScope = function(model, oldModel, isInit) { if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } this.maybeSetScopeValue('icon', model, oldModel, this.iconKey, this.evalModelHandle, isInit, this.setIcon); this.maybeSetScopeValue('coords', model, oldModel, this.coordsKey, this.evalModelHandle, isInit, this.setCoords); this.maybeSetScopeValue('labelContent', model, oldModel, this.labelContentKey, this.evalModelHandle, isInit); this.maybeSetScopeValue('click', model, oldModel, this.clickKey, this.evalModelHandle, isInit); return this.createMarker(model, oldModel, isInit); }; MarkerChildModel.prototype.createMarker = function(model, oldModel, isInit) { var _this = this; if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } return this.maybeSetScopeValue('options', model, oldModel, this.optionsKey, function(lModel, lModelKey) { var value; if (lModel === void 0) { return void 0; } value = lModelKey === 'self' ? lModel : lModel[lModelKey]; if (value === void 0) { return value = lModelKey === void 0 ? _this.defaults : _this.myScope.options; } else { return value; } }, isInit, this.setOptions); }; MarkerChildModel.prototype.evalModelHandle = function(model, modelKey) { if (model === void 0) { return void 0; } if (modelKey === 'self') { return model; } else { return model[modelKey]; } }; MarkerChildModel.prototype.maybeSetScopeValue = function(scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter) { var newValue, oldVal; if (gSetter == null) { gSetter = void 0; } if (oldModel === void 0) { this.myScope[scopePropName] = evaluate(model, modelKey); if (!isInit) { if (gSetter != null) { gSetter(this.myScope); } } return; } oldVal = evaluate(oldModel, modelKey); newValue = evaluate(model, modelKey); if (newValue !== oldVal && this.myScope[scopePropName] !== newValue) { this.myScope[scopePropName] = newValue; if (!isInit) { if (gSetter != null) { gSetter(this.myScope); } return this.gMarkerManager.draw(); } } }; MarkerChildModel.prototype.destroy = function() { return this.myScope.$destroy(); }; MarkerChildModel.prototype.setCoords = function(scope) { if (scope.$id !== this.myScope.$id || this.gMarker === void 0) { return; } if ((scope.coords != null)) { if ((this.scope.coords.latitude == null) || (this.scope.coords.longitude == null)) { this.$log.error("MarkerChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(this.model))); return; } this.gMarker.setPosition(new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude)); this.gMarker.setVisible((scope.coords.latitude != null) && (scope.coords.longitude != null)); this.gMarkerManager.remove(this.gMarker); return this.gMarkerManager.add(this.gMarker); } else { return this.gMarkerManager.remove(this.gMarker); } }; MarkerChildModel.prototype.setIcon = function(scope) { if (scope.$id !== this.myScope.$id || this.gMarker === void 0) { return; } this.gMarkerManager.remove(this.gMarker); this.gMarker.setIcon(scope.icon); this.gMarkerManager.add(this.gMarker); this.gMarker.setPosition(new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude)); return this.gMarker.setVisible(scope.coords.latitude && (scope.coords.longitude != null)); }; MarkerChildModel.prototype.setOptions = function(scope) { var _ref, _this = this; if (scope.$id !== this.myScope.$id) { return; } if (this.gMarker != null) { this.gMarkerManager.remove(this.gMarker); delete this.gMarker; } if (!((_ref = scope.coords) != null ? _ref : typeof scope.icon === "function" ? scope.icon(scope.options != null) : void 0)) { return; } this.opts = this.createMarkerOptions(scope.coords, scope.icon, scope.options); delete this.gMarker; if (this.isLabelDefined(scope)) { this.gMarker = new MarkerWithLabel(this.setLabelOptions(this.opts, scope)); } else { this.gMarker = new google.maps.Marker(this.opts); } this.gMarkerManager.add(this.gMarker); return google.maps.event.addListener(this.gMarker, 'click', function() { if (_this.doClick && (_this.myScope.click != null)) { return _this.myScope.click(); } }); }; MarkerChildModel.prototype.isLabelDefined = function(scope) { return scope.labelContent != null; }; MarkerChildModel.prototype.setLabelOptions = function(opts, scope) { opts.labelAnchor = this.getLabelPositionPoint(scope.labelAnchor); opts.labelClass = scope.labelClass; opts.labelContent = scope.labelContent; return opts; }; MarkerChildModel.prototype.watchDestroy = function(scope) { var _this = this; return scope.$on("$destroy", function() { var self; if (_this.gMarker != null) { _this.gMarkerManager.remove(_this.gMarker); delete _this.gMarker; } return self = void 0; }); }; return MarkerChildModel; })(oo.BaseObject); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.child", function() { return this.WindowChildModel = (function(_super) { __extends(WindowChildModel, _super); WindowChildModel.include(directives.api.utils.GmapUtil); function WindowChildModel(scope, opts, isIconVisibleOnClick, mapCtrl, markerCtrl, $http, $templateCache, $compile, element, needToManualDestroy) { this.element = element; if (needToManualDestroy == null) { needToManualDestroy = false; } this.destroy = __bind(this.destroy, this); this.hideWindow = __bind(this.hideWindow, this); this.getLatestPosition = __bind(this.getLatestPosition, this); this.showWindow = __bind(this.showWindow, this); this.handleClick = __bind(this.handleClick, this); this.watchCoords = __bind(this.watchCoords, this); this.watchShow = __bind(this.watchShow, this); this.createGWin = __bind(this.createGWin, this); this.scope = scope; this.opts = opts; this.mapCtrl = mapCtrl; this.markerCtrl = markerCtrl; this.isIconVisibleOnClick = isIconVisibleOnClick; this.initialMarkerVisibility = this.markerCtrl != null ? this.markerCtrl.getVisible() : false; this.$log = directives.api.utils.Logger; this.$http = $http; this.$templateCache = $templateCache; this.$compile = $compile; this.createGWin(); if (this.markerCtrl != null) { this.markerCtrl.setClickable(true); } this.handleClick(); this.watchShow(); this.watchCoords(); this.needToManualDestroy = needToManualDestroy; this.$log.info(this); } WindowChildModel.prototype.createGWin = function(createOpts) { var _this = this; if (createOpts == null) { createOpts = false; } if ((this.gWin == null) && createOpts) { this.opts = this.markerCtrl != null ? this.createWindowOptions(this.markerCtrl, this.scope, this.element.html(), {}) : {}; } if ((this.opts != null) && this.gWin === void 0) { this.gWin = new google.maps.InfoWindow(this.opts); return google.maps.event.addListener(this.gWin, 'closeclick', function() { if (_this.markerCtrl != null) { _this.markerCtrl.setVisible(_this.initialMarkerVisibility); } if (_this.scope.closeClick != null) { return _this.scope.closeClick(); } }); } }; WindowChildModel.prototype.watchShow = function() { var _this = this; return this.scope.$watch('show', function(newValue, oldValue) { if (newValue !== oldValue) { if (newValue) { return _this.showWindow(); } else { return _this.hideWindow(); } } else { if (_this.gWin != null) { if (newValue && !_this.gWin.getMap()) { return _this.showWindow(); } } } }, true); }; WindowChildModel.prototype.watchCoords = function() { var scope, _this = this; scope = this.markerCtrl != null ? this.scope.$parent : this.scope; return scope.$watch('coords', function(newValue, oldValue) { if (newValue !== oldValue) { if (newValue == null) { return _this.hideWindow(); } else { if ((newValue.latitude == null) || (newValue.longitude == null)) { _this.$log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model))); return; } return _this.gWin.setPosition(new google.maps.LatLng(newValue.latitude, newValue.longitude)); } } }, true); }; WindowChildModel.prototype.handleClick = function() { var _this = this; if (this.markerCtrl != null) { return google.maps.event.addListener(this.markerCtrl, 'click', function() { var pos; if ((_this.gWin == null) && (_this.opts == null)) { _this.createGWin(true); } else { if (_this.gWin == null) { _this.createGWin(); } } pos = _this.markerCtrl.getPosition(); if (_this.gWin != null) { _this.gWin.setPosition(pos); _this.gWin.open(_this.mapCtrl); } _this.initialMarkerVisibility = _this.markerCtrl.getVisible(); return _this.markerCtrl.setVisible(_this.isIconVisibleOnClick); }); } }; WindowChildModel.prototype.showWindow = function() { var _this = this; if (this.scope.templateUrl) { if (this.gWin) { return this.$http.get(this.scope.templateUrl, { cache: this.$templateCache }).then(function(content) { var compiled, templateScope; templateScope = _this.scope.$new(); if (angular.isDefined(_this.scope.templateParameter)) { templateScope.parameter = _this.scope.templateParameter; } compiled = _this.$compile(content.data)(templateScope); _this.gWin.setContent(compiled.get(0)); return _this.gWin.open(_this.mapCtrl); }); } } else { if (this.gWin != null) { return this.gWin.open(this.mapCtrl); } } }; WindowChildModel.prototype.getLatestPosition = function() { if ((this.gWin != null) && (this.markerCtrl != null)) { return this.gWin.setPosition(this.markerCtrl.getPosition()); } }; WindowChildModel.prototype.hideWindow = function() { if (this.gWin != null) { return this.gWin.close(); } }; WindowChildModel.prototype.destroy = function() { var self; this.hideWindow(this.gWin); if ((this.scope != null) && this.needToManualDestroy) { this.scope.$destroy(); } delete this.gWin; return self = void 0; }; return WindowChildModel; })(oo.BaseObject); }); }).call(this); /* - interface for all markers to derrive from - to enforce a minimum set of requirements - attributes - coords - icon - implementation needed on watches */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.parent", function() { return this.IMarkerParentModel = (function(_super) { __extends(IMarkerParentModel, _super); IMarkerParentModel.prototype.DEFAULTS = {}; IMarkerParentModel.prototype.isFalse = function(value) { return ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO'].indexOf(value) !== -1; }; function IMarkerParentModel(scope, element, attrs, mapCtrl, $timeout) { var self, _this = this; this.scope = scope; this.element = element; this.attrs = attrs; this.mapCtrl = mapCtrl; this.$timeout = $timeout; this.linkInit = __bind(this.linkInit, this); this.onDestroy = __bind(this.onDestroy, this); this.onWatch = __bind(this.onWatch, this); this.watch = __bind(this.watch, this); this.validateScope = __bind(this.validateScope, this); this.onTimeOut = __bind(this.onTimeOut, this); self = this; this.$log = directives.api.utils.Logger; if (!this.validateScope(scope)) { return; } this.doClick = angular.isDefined(attrs.click); if (scope.options != null) { this.DEFAULTS = scope.options; } this.$timeout(function() { _this.watch('coords', scope); _this.watch('icon', scope); _this.watch('options', scope); _this.onTimeOut(scope); return scope.$on("$destroy", function() { return _this.onDestroy(scope); }); }); } IMarkerParentModel.prototype.onTimeOut = function(scope) {}; IMarkerParentModel.prototype.validateScope = function(scope) { var ret; if (scope == null) { return false; } ret = scope.coords != null; if (!ret) { this.$log.error(this.constructor.name + ": no valid coords attribute found"); } return ret; }; IMarkerParentModel.prototype.watch = function(propNameToWatch, scope) { var _this = this; return scope.$watch(propNameToWatch, function(newValue, oldValue) { if (newValue !== oldValue) { return _this.onWatch(propNameToWatch, scope, newValue, oldValue); } }, true); }; IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) { throw new Exception("Not Implemented!!"); }; IMarkerParentModel.prototype.onDestroy = function(scope) { throw new Exception("Not Implemented!!"); }; IMarkerParentModel.prototype.linkInit = function(element, mapCtrl, scope, animate) { throw new Exception("Not Implemented!!"); }; return IMarkerParentModel; })(oo.BaseObject); }); }).call(this); /* - interface directive for all window(s) to derrive from */ (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.parent", function() { return this.IWindowParentModel = (function(_super) { __extends(IWindowParentModel, _super); IWindowParentModel.include(directives.api.utils.GmapUtil); IWindowParentModel.prototype.DEFAULTS = {}; function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) { var self; self = this; this.$log = directives.api.utils.Logger; this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; if (scope.options != null) { this.DEFAULTS = scope.options; } } return IWindowParentModel; })(oo.BaseObject); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.parent", function() { return this.LayerParentModel = (function(_super) { __extends(LayerParentModel, _super); function LayerParentModel(scope, element, attrs, mapCtrl, $timeout, onLayerCreated, $log) { var _this = this; this.scope = scope; this.element = element; this.attrs = attrs; this.mapCtrl = mapCtrl; this.$timeout = $timeout; this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0; this.$log = $log != null ? $log : directives.api.utils.Logger; this.createGoogleLayer = __bind(this.createGoogleLayer, this); if (this.attrs.type == null) { this.$log.info("type attribute for the layer directive is mandatory. Layer creation aborted!!"); return; } this.createGoogleLayer(); this.gMap = void 0; this.doShow = true; this.$timeout(function() { _this.gMap = mapCtrl.getMap(); if (angular.isDefined(_this.attrs.show)) { _this.doShow = _this.scope.show; } if (_this.doShow !== null && _this.doShow && _this.Map !== null) { _this.layer.setMap(_this.gMap); } _this.scope.$watch("show", function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.layer.setMap(_this.gMap); } else { return _this.layer.setMap(null); } } }, true); _this.scope.$watch("options", function(newValue, oldValue) { if (newValue !== oldValue) { _this.layer.setMap(null); _this.layer = null; return _this.createGoogleLayer(); } }, true); return _this.scope.$on("$destroy", function() { return this.layer.setMap(null); }); }); } LayerParentModel.prototype.createGoogleLayer = function() { var _this = this; if (this.attrs.options != null) { this.layer = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type]() : new google.maps[this.attrs.namespace][this.attrs.type](); } else { this.layer = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type](this.scope.options) : new google.maps[this.attrs.namespace][this.attrs.type](this.scope.options); } return this.$timeout(function() { var fn; if ((_this.layer != null) && (_this.onLayerCreated != null)) { fn = _this.onLayerCreated(_this.scope, _this.layer); if (fn) { return fn(_this.layer); } } }); }; return LayerParentModel; })(oo.BaseObject); }); }).call(this); /* Basic Directive api for a marker. Basic in the sense that this directive contains 1:1 on scope and model. Thus there will be one html element per marker within the directive. */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.parent", function() { return this.MarkerParentModel = (function(_super) { __extends(MarkerParentModel, _super); MarkerParentModel.include(directives.api.utils.GmapUtil); function MarkerParentModel(scope, element, attrs, mapCtrl, $timeout) { this.onDestroy = __bind(this.onDestroy, this); this.onWatch = __bind(this.onWatch, this); this.onTimeOut = __bind(this.onTimeOut, this); var self; MarkerParentModel.__super__.constructor.call(this, scope, element, attrs, mapCtrl, $timeout); self = this; } MarkerParentModel.prototype.onTimeOut = function(scope) { var opts, _this = this; opts = this.createMarkerOptions(scope.coords, scope.icon, scope.options, this.mapCtrl.getMap()); this.scope.gMarker = new google.maps.Marker(opts); google.maps.event.addListener(this.scope.gMarker, 'click', function() { if (_this.doClick && (scope.click != null)) { return _this.$timeout(function() { return _this.scope.click(); }); } }); this.setEvents(this.scope.gMarker, scope); return this.$log.info(this); }; MarkerParentModel.prototype.onWatch = function(propNameToWatch, scope) { switch (propNameToWatch) { case 'coords': if ((scope.coords != null) && (this.scope.gMarker != null)) { this.scope.gMarker.setMap(this.mapCtrl.getMap()); this.scope.gMarker.setPosition(new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude)); this.scope.gMarker.setVisible((scope.coords.latitude != null) && (scope.coords.longitude != null)); return this.scope.gMarker.setOptions(scope.options); } else { return this.scope.gMarker.setMap(null); } break; case 'icon': if ((scope.icon != null) && (scope.coords != null) && (this.scope.gMarker != null)) { this.scope.gMarker.setOptions(scope.options); this.scope.gMarker.setIcon(scope.icon); this.scope.gMarker.setMap(null); this.scope.gMarker.setMap(this.mapCtrl.getMap()); this.scope.gMarker.setPosition(new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude)); return this.scope.gMarker.setVisible(scope.coords.latitude && (scope.coords.longitude != null)); } break; case 'options': if ((scope.coords != null) && (scope.icon != null) && scope.options) { if (this.scope.gMarker != null) { this.scope.gMarker.setMap(null); } delete this.scope.gMarker; return this.scope.gMarker = new google.maps.Marker(this.createMarkerOptions(scope.coords, scope.icon, scope.options, this.mapCtrl.getMap())); } } }; MarkerParentModel.prototype.onDestroy = function(scope) { var self; if (this.scope.gMarker === void 0) { self = void 0; return; } this.scope.gMarker.setMap(null); delete this.scope.gMarker; return self = void 0; }; MarkerParentModel.prototype.setEvents = function(marker, scope) { var eventHandler, eventName, _ref, _results; if (angular.isDefined(scope.events) && (scope.events != null) && angular.isObject(scope.events)) { _ref = scope.events; _results = []; for (eventName in _ref) { eventHandler = _ref[eventName]; if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) { _results.push(google.maps.event.addListener(marker, eventName, function() { return eventHandler.apply(scope, [marker, eventName, arguments]); })); } else { _results.push(void 0); } } return _results; } }; return MarkerParentModel; })(directives.api.models.parent.IMarkerParentModel); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.parent", function() { return this.MarkersParentModel = (function(_super) { __extends(MarkersParentModel, _super); MarkersParentModel.include(directives.api.utils.ModelsWatcher); function MarkersParentModel(scope, element, attrs, mapCtrl, $timeout) { this.fit = __bind(this.fit, this); this.onDestroy = __bind(this.onDestroy, this); this.onWatch = __bind(this.onWatch, this); this.reBuildMarkers = __bind(this.reBuildMarkers, this); this.createMarkers = __bind(this.createMarkers, this); this.validateScope = __bind(this.validateScope, this); this.onTimeOut = __bind(this.onTimeOut, this); var self; MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, mapCtrl, $timeout); self = this; this.markersIndex = 0; this.gMarkerManager = void 0; this.scope = scope; this.scope.markerModels = []; this.bigGulp = directives.api.utils.AsyncProcessor; this.$timeout = $timeout; this.$log.info(this); } MarkersParentModel.prototype.onTimeOut = function(scope) { this.watch('models', scope); this.watch('doCluster', scope); this.watch('clusterOptions', scope); this.watch('fit', scope); return this.createMarkers(scope); }; MarkersParentModel.prototype.validateScope = function(scope) { var modelsNotDefined; modelsNotDefined = angular.isUndefined(scope.models) || scope.models === void 0; if (modelsNotDefined) { this.$log.error(this.constructor.name + ": no valid models attribute found"); } return MarkersParentModel.__super__.validateScope.call(this, scope) || modelsNotDefined; }; MarkersParentModel.prototype.createMarkers = function(scope) { var markers, _this = this; if ((scope.doCluster != null) && scope.doCluster === true) { if (scope.clusterOptions != null) { if (this.gMarkerManager === void 0) { this.gMarkerManager = new directives.api.managers.ClustererMarkerManager(this.mapCtrl.getMap(), void 0, scope.clusterOptions); } else { if (this.gMarkerManager.opt_options !== scope.clusterOptions) { this.gMarkerManager = new directives.api.managers.ClustererMarkerManager(this.mapCtrl.getMap(), void 0, scope.clusterOptions); } } } else { this.gMarkerManager = new directives.api.managers.ClustererMarkerManager(this.mapCtrl.getMap()); } } else { this.gMarkerManager = new directives.api.managers.MarkerManager(this.mapCtrl.getMap()); } markers = []; scope.isMarkerModelsReady = false; return this.bigGulp.handleLargeArray(scope.models, function(model) { var child; scope.doRebuild = true; child = new directives.api.models.child.MarkerChildModel(_this.markersIndex, model, scope, _this.mapCtrl, _this.$timeout, _this.DEFAULTS, _this.doClick, _this.gMarkerManager); _this.$log.info('child', child, 'markers', markers); markers.push(child); return _this.markersIndex++; }, (function() {}), function() { _this.gMarkerManager.draw(); scope.markerModels = markers; if (angular.isDefined(_this.attrs.fit) && (scope.fit != null) && scope.fit) { _this.fit(); } scope.isMarkerModelsReady = true; if (scope.onMarkerModelsReady != null) { return scope.onMarkerModelsReady(scope); } }); }; MarkersParentModel.prototype.reBuildMarkers = function(scope) { var _this = this; if (!scope.doRebuild && scope.doRebuild !== void 0) { return; } _.each(scope.markerModels, function(oldM) { return oldM.destroy(); }); this.markersIndex = 0; if (this.gMarkerManager != null) { this.gMarkerManager.clear(); } return this.createMarkers(scope); }; MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) { if (propNameToWatch === 'models') { if (!this.didModelsChange(newValue, oldValue)) { return; } } if (propNameToWatch === 'options' && (newValue != null)) { this.DEFAULTS = newValue; return; } return this.reBuildMarkers(scope); }; MarkersParentModel.prototype.onDestroy = function(scope) { var model, _i, _len, _ref; _ref = scope.markerModels; for (_i = 0, _len = _ref.length; _i < _len; _i++) { model = _ref[_i]; model.destroy(); } if (this.gMarkerManager != null) { return this.gMarkerManager.clear(); } }; MarkersParentModel.prototype.fit = function() { var bounds, everSet, _this = this; if (this.mapCtrl && (this.scope.markerModels != null) && this.scope.markerModels.length > 0) { bounds = new google.maps.LatLngBounds(); everSet = false; _.each(this.scope.markerModels, function(childModelMarker) { if (childModelMarker.gMarker != null) { if (!everSet) { everSet = true; } return bounds.extend(childModelMarker.gMarker.getPosition()); } }); if (everSet) { return this.mapCtrl.getMap().fitBounds(bounds); } } }; return MarkersParentModel; })(directives.api.models.parent.IMarkerParentModel); }); }).call(this); /* Windows directive where many windows map to the models property */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.parent", function() { return this.WindowsParentModel = (function(_super) { __extends(WindowsParentModel, _super); WindowsParentModel.include(directives.api.utils.ModelsWatcher); function WindowsParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache, $interpolate) { this.interpolateContent = __bind(this.interpolateContent, this); this.setChildScope = __bind(this.setChildScope, this); this.createWindow = __bind(this.createWindow, this); this.setContentKeys = __bind(this.setContentKeys, this); this.createChildScopesWindows = __bind(this.createChildScopesWindows, this); this.onMarkerModelsReady = __bind(this.onMarkerModelsReady, this); this.watchOurScope = __bind(this.watchOurScope, this); this.destroy = __bind(this.destroy, this); this.watchDestroy = __bind(this.watchDestroy, this); this.watchModels = __bind(this.watchModels, this); this.watch = __bind(this.watch, this); var name, self, _i, _len, _ref, _this = this; WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache, $interpolate); self = this; this.$interpolate = $interpolate; this.windows = []; this.windwsIndex = 0; this.scopePropNames = ['show', 'coords', 'templateUrl', 'templateParameter', 'isIconVisibleOnClick', 'closeClick']; _ref = this.scopePropNames; for (_i = 0, _len = _ref.length; _i < _len; _i++) { name = _ref[_i]; this[name + 'Key'] = void 0; } this.linked = new directives.api.utils.Linked(scope, element, attrs, ctrls); this.models = void 0; this.contentKeys = void 0; this.isIconVisibleOnClick = void 0; this.firstTime = true; this.bigGulp = directives.api.utils.AsyncProcessor; this.$log.info(self); this.$timeout(function() { _this.watchOurScope(scope); return _this.createChildScopesWindows(); }, 50); } WindowsParentModel.prototype.watch = function(scope, name, nameKey) { var _this = this; return scope.$watch(name, function(newValue, oldValue) { var model, _i, _len, _ref, _results; if (newValue !== oldValue) { _this[nameKey] = typeof newValue === 'function' ? newValue() : newValue; _ref = _this.windows; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { model = _ref[_i]; _results.push((function(model) { return model.scope[name] = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; })(model)); } return _results; } }, true); }; WindowsParentModel.prototype.watchModels = function(scope) { var _this = this; return scope.$watch('models', function(newValue, oldValue) { if (_this.didModelsChange(newValue, oldValue)) { _this.destroy(); return _this.createChildScopesWindows(); } }); }; WindowsParentModel.prototype.watchDestroy = function(scope) { var _this = this; return scope.$on("$destroy", function() { return _this.destroy(); }); }; WindowsParentModel.prototype.destroy = function() { var _this = this; _.each(this.windows, function(model) { return model.destroy(); }); delete this.windows; this.windows = []; return this.windowsIndex = 0; }; WindowsParentModel.prototype.watchOurScope = function(scope) { var _this = this; return _.each(this.scopePropNames, function(name) { var nameKey; nameKey = name + 'Key'; _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name]; return _this.watch(scope, name, nameKey); }); }; WindowsParentModel.prototype.onMarkerModelsReady = function(scope) { var _this = this; this.destroy(); this.models = scope.models; if (this.firstTime) { this.watchDestroy(scope); } this.setContentKeys(scope.models); return this.bigGulp.handleLargeArray(scope.markerModels, function(mm) { return _this.createWindow(mm.model, mm.gMarker, _this.gMap); }, (function() {}), function() { return _this.firstTime = false; }); }; WindowsParentModel.prototype.createChildScopesWindows = function() { /* being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl) we will assume that all scope values are string expressions either pointing to a key (propName) or using 'self' to point the model as container/object of interest. This may force redundant information into the model, but this appears to be the most flexible approach. */ var markersScope, modelsNotDefined, _this = this; this.isIconVisibleOnClick = true; if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) { this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick; } this.gMap = this.linked.ctrls[0].getMap(); markersScope = this.linked.ctrls.length > 1 && (this.linked.ctrls[1] != null) ? this.linked.ctrls[1].getMarkersScope() : void 0; modelsNotDefined = angular.isUndefined(this.linked.scope.models); if (modelsNotDefined && (markersScope === void 0 || (markersScope.markerModels === void 0 && markersScope.models === void 0))) { this.$log.info("No models to create windows from! Need direct models or models derrived from markers!"); return; } if (this.gMap != null) { if (this.linked.scope.models != null) { this.models = this.linked.scope.models; if (this.firstTime) { this.watchModels(this.linked.scope); this.watchDestroy(this.linked.scope); } this.setContentKeys(this.linked.scope.models); return this.bigGulp.handleLargeArray(this.linked.scope.models, function(model) { return _this.createWindow(model, void 0, _this.gMap); }, (function() {}), function() { return _this.firstTime = false; }); } else { markersScope.onMarkerModelsReady = this.onMarkerModelsReady; if (markersScope.isMarkerModelsReady) { return this.onMarkerModelsReady(markersScope); } } } }; WindowsParentModel.prototype.setContentKeys = function(models) { if (models.length > 0) { return this.contentKeys = Object.keys(models[0]); } }; WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) { /* Create ChildScope to Mimmick an ng-repeat created scope, must define the below scope scope= { coords: '=coords', show: '&show', templateUrl: '=templateurl', templateParameter: '=templateparameter', isIconVisibleOnClick: '=isiconvisibleonclick', closeClick: '&closeclick' } */ var childScope, opts, parsedContent, _this = this; childScope = this.linked.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }, true); parsedContent = this.interpolateContent(this.linked.element.html(), model); opts = this.createWindowOptions(gMarker, childScope, parsedContent, this.DEFAULTS); return this.windows.push(new directives.api.models.child.WindowChildModel(childScope, opts, this.isIconVisibleOnClick, gMap, gMarker, this.$http, this.$templateCache, this.$compile, true)); }; WindowsParentModel.prototype.setChildScope = function(childScope, model) { var name, _fn, _i, _len, _ref, _this = this; _ref = this.scopePropNames; _fn = function(name) { var nameKey, newValue; nameKey = name + 'Key'; newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; if (newValue !== childScope[name]) { return childScope[name] = newValue; } }; for (_i = 0, _len = _ref.length; _i < _len; _i++) { name = _ref[_i]; _fn(name); } return childScope.model = model; }; WindowsParentModel.prototype.interpolateContent = function(content, model) { var exp, interpModel, key, _i, _len, _ref; if (this.contentKeys === void 0 || this.contentKeys.length === 0) { return; } exp = this.$interpolate(content); interpModel = {}; _ref = this.contentKeys; for (_i = 0, _len = _ref.length; _i < _len; _i++) { key = _ref[_i]; interpModel[key] = model[key]; } return exp(interpModel); }; return WindowsParentModel; })(directives.api.models.parent.IWindowParentModel); }); }).call(this); /* - interface for all labels to derrive from - to enforce a minimum set of requirements - attributes - content - anchor - implementation needed on watches */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.ILabel = (function(_super) { __extends(ILabel, _super); function ILabel($timeout) { this.link = __bind(this.link, this); var self; self = this; this.restrict = 'ECMA'; this.replace = true; this.template = void 0; this.require = void 0; this.transclude = true; this.priority = -100; this.scope = { labelContent: '=content', labelAnchor: '@anchor', labelClass: '@class', labelStyle: '=style' }; this.$log = directives.api.utils.Logger; this.$timeout = $timeout; } ILabel.prototype.link = function(scope, element, attrs, ctrl) { throw new Exception("Not Implemented!!"); }; return ILabel; })(oo.BaseObject); }); }).call(this); /* - interface for all markers to derrive from - to enforce a minimum set of requirements - attributes - coords - icon - implementation needed on watches */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.IMarker = (function(_super) { __extends(IMarker, _super); function IMarker($timeout) { this.link = __bind(this.link, this); var self; self = this; this.$log = directives.api.utils.Logger; this.$timeout = $timeout; this.restrict = 'ECMA'; this.require = '^googleMap'; this.priority = -1; this.transclude = true; this.replace = true; this.scope = { coords: '=coords', icon: '=icon', click: '&click', options: '=options', events: '=events' }; } IMarker.prototype.controller = [ '$scope', '$element', function($scope, $element) { throw new Exception("Not Implemented!!"); } ]; IMarker.prototype.link = function(scope, element, attrs, ctrl) { throw new Exception("Not implemented!!"); }; return IMarker; })(oo.BaseObject); }); }).call(this); /* - interface directive for all window(s) to derrive from */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.IWindow = (function(_super) { __extends(IWindow, _super); IWindow.include(directives.api.utils.ChildEvents); function IWindow($timeout, $compile, $http, $templateCache) { var self; this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; this.link = __bind(this.link, this); self = this; this.restrict = 'ECMA'; this.template = void 0; this.transclude = true; this.priority = -100; this.require = void 0; this.replace = true; this.scope = { coords: '=coords', show: '=show', templateUrl: '=templateurl', templateParameter: '=templateparameter', isIconVisibleOnClick: '=isiconvisibleonclick', closeClick: '&closeclick', options: '=options' }; this.$log = directives.api.utils.Logger; } IWindow.prototype.link = function(scope, element, attrs, ctrls) { throw new Exception("Not Implemented!!"); }; return IWindow; })(oo.BaseObject); }); }).call(this); /* Basic Directive api for a label. Basic in the sense that this directive contains 1:1 on scope and model. Thus there will be one html element per marker within the directive. */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.Label = (function(_super) { __extends(Label, _super); function Label($timeout) { this.link = __bind(this.link, this); var self; Label.__super__.constructor.call(this, $timeout); self = this; this.require = '^marker'; this.template = '<span class="angular-google-maps-marker-label" ng-transclude></span>'; this.$log.info(this); } Label.prototype.link = function(scope, element, attrs, ctrl) { var _this = this; return this.$timeout(function() { var label, markerCtrl; markerCtrl = ctrl.getMarkerScope().gMarker; if (markerCtrl != null) { label = new directives.api.models.child.MarkerLabelChildModel(markerCtrl, scope); } return scope.$on("$destroy", function() { return label.destroy(); }); }, directives.api.utils.GmapUtil.defaultDelay + 25); }; return Label; })(directives.api.ILabel); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.Layer = (function(_super) { __extends(Layer, _super); function Layer($timeout) { this.$timeout = $timeout; this.link = __bind(this.link, this); this.$log = directives.api.utils.Logger; this.restrict = "ECMA"; this.require = "^googleMap"; this.priority = -1; this.transclude = true; this.template = '<span class=\"angular-google-map-layer\" ng-transclude></span>'; this.replace = true; this.scope = { show: "=show", type: "=type", namespace: "=namespace", options: '=options', onCreated: '&oncreated' }; } Layer.prototype.link = function(scope, element, attrs, mapCtrl) { if (attrs.oncreated != null) { return new directives.api.models.parent.LayerParentModel(scope, element, attrs, mapCtrl, this.$timeout, scope.onCreated); } else { return new directives.api.models.parent.LayerParentModel(scope, element, attrs, mapCtrl, this.$timeout); } }; return Layer; })(oo.BaseObject); }); }).call(this); /* Basic Directive api for a marker. Basic in the sense that this directive contains 1:1 on scope and model. Thus there will be one html element per marker within the directive. */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.Marker = (function(_super) { __extends(Marker, _super); function Marker($timeout) { this.link = __bind(this.link, this); var self; Marker.__super__.constructor.call(this, $timeout); self = this; this.template = '<span class="angular-google-map-marker" ng-transclude></span>'; this.$log.info(this); } Marker.prototype.controller = [ '$scope', '$element', function($scope, $element) { return { getMarkerScope: function() { return $scope; } }; } ]; Marker.prototype.link = function(scope, element, attrs, ctrl) { return new directives.api.models.parent.MarkerParentModel(scope, element, attrs, ctrl, this.$timeout); }; return Marker; })(directives.api.IMarker); }); }).call(this); /* Markers will map icon and coords differently than directibes.api.Marker. This is because Scope and the model marker are not 1:1 in this setting. - icon - will be the iconKey to the marker value ie: to get the icon marker[iconKey] - coords - will be the coordsKey to the marker value ie: to get the icon marker[coordsKey] - watches from IMarker reflect that the look up key for a value has changed and not the actual icon or coords itself - actual changes to a model are tracked inside directives.api.model.MarkerModel */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.Markers = (function(_super) { __extends(Markers, _super); function Markers($timeout) { this.link = __bind(this.link, this); var self; Markers.__super__.constructor.call(this, $timeout); self = this; this.template = '<span class="angular-google-map-markers" ng-transclude></span>'; this.scope.models = '=models'; this.scope.doCluster = '=docluster'; this.scope.clusterOptions = '=clusteroptions'; this.scope.fit = '=fit'; this.scope.labelContent = '=labelcontent'; this.scope.labelAnchor = '@labelanchor'; this.scope.labelClass = '@labelclass'; this.$timeout = $timeout; this.$log.info(this); } Markers.prototype.controller = [ '$scope', '$element', function($scope, $element) { return { getMarkersScope: function() { return $scope; } }; } ]; Markers.prototype.link = function(scope, element, attrs, ctrl) { return new directives.api.models.parent.MarkersParentModel(scope, element, attrs, ctrl, this.$timeout); }; return Markers; })(directives.api.IMarker); }); }).call(this); /* Window directive for GoogleMap Info Windows, where ng-repeat is being used.... Where Html DOM element is 1:1 on Scope and a Model */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.Window = (function(_super) { __extends(Window, _super); Window.include(directives.api.utils.GmapUtil); function Window($timeout, $compile, $http, $templateCache) { this.link = __bind(this.link, this); var self; Window.__super__.constructor.call(this, $timeout, $compile, $http, $templateCache); self = this; this.require = ['^googleMap', '^?marker']; this.template = '<span class="angular-google-maps-window" ng-transclude></span>'; this.$log.info(self); } Window.prototype.link = function(scope, element, attrs, ctrls) { var _this = this; return this.$timeout(function() { var defaults, hasScopeCoords, isIconVisibleOnClick, mapCtrl, markerCtrl, markerScope, opts, window; isIconVisibleOnClick = true; if (angular.isDefined(attrs.isiconvisibleonclick)) { isIconVisibleOnClick = scope.isIconVisibleOnClick; } mapCtrl = ctrls[0].getMap(); markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1].getMarkerScope().gMarker : void 0; defaults = scope.options != null ? scope.options : {}; hasScopeCoords = (scope != null) && (scope.coords != null) && (scope.coords.latitude != null) && (scope.coords.longitude != null); opts = hasScopeCoords ? _this.createWindowOptions(markerCtrl, scope, element.html(), defaults) : void 0; if (mapCtrl != null) { window = new directives.api.models.child.WindowChildModel(scope, opts, isIconVisibleOnClick, mapCtrl, markerCtrl, _this.$http, _this.$templateCache, _this.$compile, element); } scope.$on("$destroy", function() { return window.destroy(); }); if (ctrls[1] != null) { markerScope = ctrls[1].getMarkerScope(); markerScope.$watch('coords', function(newValue, oldValue) { if (newValue == null) { return window.hideWindow(); } }); markerScope.$watch('coords.latitude', function(newValue, oldValue) { if (newValue !== oldValue) { return window.getLatestPosition(); } }); } if ((_this.onChildCreation != null) && (window != null)) { return _this.onChildCreation(window); } }, directives.api.utils.GmapUtil.defaultDelay + 25); }; return Window; })(directives.api.IWindow); }); }).call(this); /* Windows directive where many windows map to the models property */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.Windows = (function(_super) { __extends(Windows, _super); function Windows($timeout, $compile, $http, $templateCache, $interpolate) { this.link = __bind(this.link, this); var self; Windows.__super__.constructor.call(this, $timeout, $compile, $http, $templateCache); self = this; this.$interpolate = $interpolate; this.require = ['^googleMap', '^?markers']; this.template = '<span class="angular-google-maps-windows" ng-transclude></span>'; this.scope.models = '=models'; this.$log.info(self); } Windows.prototype.link = function(scope, element, attrs, ctrls) { return new directives.api.models.parent.WindowsParentModel(scope, element, attrs, ctrls, this.$timeout, this.$compile, this.$http, this.$templateCache, this.$interpolate); }; return Windows; })(directives.api.IWindow); }); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Nick Baugh - https://github.com/niftylettuce */ (function() { angular.module("google-maps").directive("googleMap", [ "$log", "$timeout", function($log, $timeout) { "use strict"; var DEFAULTS, isTrue; isTrue = function(val) { return angular.isDefined(val) && val !== null && val === true || val === "1" || val === "y" || val === "true"; }; directives.api.utils.Logger.logger = $log; DEFAULTS = { mapTypeId: google.maps.MapTypeId.ROADMAP }; return { self: this, restrict: "ECMA", transclude: true, replace: false, template: "<div class=\"angular-google-map\"><div class=\"angular-google-map-container\"></div><div ng-transclude style=\"display: none\"></div></div>", scope: { center: "=center", zoom: "=zoom", dragging: "=dragging", refresh: "&refresh", windows: "=windows", options: "=options", events: "=events", styles: "=styles", bounds: "=bounds" }, controller: [ "$scope", function($scope) { return { getMap: function() { return $scope.map; } }; } ], /* @param scope @param element @param attrs */ link: function(scope, element, attrs) { var dragging, el, eventName, getEventHandler, opts, settingCenterFromScope, type, _m, _this = this; if (!angular.isDefined(scope.center) || (!angular.isDefined(scope.center.latitude) || !angular.isDefined(scope.center.longitude))) { $log.error("angular-google-maps: could not find a valid center property"); return; } if (!angular.isDefined(scope.zoom)) { $log.error("angular-google-maps: map zoom property not set"); return; } el = angular.element(element); el.addClass("angular-google-map"); opts = { options: {} }; if (attrs.options) { opts.options = scope.options; } if (attrs.styles) { opts.styles = scope.styles; } if (attrs.type) { type = attrs.type.toUpperCase(); if (google.maps.MapTypeId.hasOwnProperty(type)) { opts.mapTypeId = google.maps.MapTypeId[attrs.type.toUpperCase()]; } else { $log.error("angular-google-maps: invalid map type \"" + attrs.type + "\""); } } _m = new google.maps.Map(el.find("div")[1], angular.extend({}, DEFAULTS, opts, { center: new google.maps.LatLng(scope.center.latitude, scope.center.longitude), draggable: isTrue(attrs.draggable), zoom: scope.zoom, bounds: scope.bounds })); dragging = false; google.maps.event.addListener(_m, "dragstart", function() { dragging = true; return _.defer(function() { return scope.$apply(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); }); google.maps.event.addListener(_m, "dragend", function() { dragging = false; return _.defer(function() { return scope.$apply(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); }); google.maps.event.addListener(_m, "drag", function() { var c; c = _m.center; return _.defer(function() { return scope.$apply(function(s) { s.center.latitude = c.lat(); return s.center.longitude = c.lng(); }); }); }); google.maps.event.addListener(_m, "zoom_changed", function() { if (scope.zoom !== _m.zoom) { return _.defer(function() { return scope.$apply(function(s) { return s.zoom = _m.zoom; }); }); } }); settingCenterFromScope = false; google.maps.event.addListener(_m, "center_changed", function() { var c; c = _m.center; if (settingCenterFromScope) { return; } return _.defer(function() { return scope.$apply(function(s) { if (!_m.dragging) { if (s.center.latitude !== c.lat()) { s.center.latitude = c.lat(); } if (s.center.longitude !== c.lng()) { return s.center.longitude = c.lng(); } } }); }); }); google.maps.event.addListener(_m, "idle", function() { var b, ne, sw; b = _m.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); return _.defer(function() { return scope.$apply(function(s) { if (s.bounds !== null && s.bounds !== undefined && s.bounds !== void 0) { s.bounds.northeast = { latitude: ne.lat(), longitude: ne.lng() }; return s.bounds.southwest = { latitude: sw.lat(), longitude: sw.lng() }; } }); }); }); if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) { getEventHandler = function(eventName) { return function() { return scope.events[eventName].apply(scope, [_m, eventName, arguments]); }; }; for (eventName in scope.events) { if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) { google.maps.event.addListener(_m, eventName, getEventHandler(eventName)); } } } scope.map = _m; google.maps.event.trigger(_m, "resize"); if (!angular.isUndefined(scope.refresh())) { scope.$watch("refresh()", function(newValue, oldValue) { var coords; if (newValue && !oldValue) { coords = new google.maps.LatLng(newValue.latitude, newValue.longitude); if (isTrue(attrs.pan)) { return _m.panTo(coords); } else { return _m.setCenter(coords); } } }); } scope.$watch("center", (function(newValue, oldValue) { var coords; if (newValue === oldValue) { return; } settingCenterFromScope = true; if (!dragging) { if ((newValue.latitude == null) || (newValue.longitude == null)) { $log.error("Invalid center for newVa;ue: " + (JSON.stringify(newValue))); } coords = new google.maps.LatLng(newValue.latitude, newValue.longitude); if (isTrue(attrs.pan)) { _m.panTo(coords); } else { _m.setCenter(coords); } } return settingCenterFromScope = false; }), true); scope.$watch("zoom", function(newValue, oldValue) { if (newValue === oldValue) { return; } return _m.setZoom(newValue); }); scope.$watch("bounds", function(newValue, oldValue) { var bounds, ne, sw; if (newValue === oldValue) { return; } if ((newValue.northeast.latitude == null) || (newValue.northeast.longitude == null) || (newValue.southwest.latitude == null) || (newValue.southwest.longitude == null)) { $log.error("Invalid map bounds for new value: " + (JSON.stringify(newValue))); return; } ne = new google.maps.LatLng(newValue.northeast.latitude, newValue.northeast.longitude); sw = new google.maps.LatLng(newValue.southwest.latitude, newValue.southwest.longitude); bounds = new google.maps.LatLngBounds(sw, ne); return _m.fitBounds(bounds); }); scope.$watch("options", function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { opts.options = newValue; if (_m != null) { return _m.setOptions(opts); } } }, true); return scope.$watch("styles", function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { opts.styles = newValue; if (_m != null) { return _m.setOptions(opts); } } }, true); } }; } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map marker directive This directive is used to create a marker on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute icon optional} string url to image used for marker icon {attribute animate optional} if set to false, the marker won't be animated (on by default) */ (function() { angular.module("google-maps").directive("marker", [ "$timeout", function($timeout) { return new directives.api.Marker($timeout); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map marker directive This directive is used to create a marker on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute icon optional} string url to image used for marker icon {attribute animate optional} if set to false, the marker won't be animated (on by default) */ (function() { angular.module("google-maps").directive("markers", [ "$timeout", function($timeout) { return new directives.api.Markers($timeout); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Bruno Queiroz, creativelikeadog@gmail.com */ /* Marker label directive This directive is used to create a marker label on an existing map. {attribute content required} content of the label {attribute anchor required} string that contains the x and y point position of the label {attribute class optional} class to DOM object {attribute style optional} style for the label */ (function() { angular.module("google-maps").directive("markerLabel", [ "$log", "$timeout", function($log, $timeout) { return new directives.api.Label($timeout); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module("google-maps").directive("polygon", [ "$log", "$timeout", function($log, $timeout) { var DEFAULTS, convertPathPoints, extendMapBounds, isTrue, validatePathPoints; validatePathPoints = function(path) { var i; i = 0; while (i < path.length) { if (angular.isUndefined(path[i].latitude) || angular.isUndefined(path[i].longitude)) { return false; } i++; } return true; }; convertPathPoints = function(path) { var i, result; result = new google.maps.MVCArray(); i = 0; while (i < path.length) { result.push(new google.maps.LatLng(path[i].latitude, path[i].longitude)); i++; } return result; }; extendMapBounds = function(map, points) { var bounds, i; bounds = new google.maps.LatLngBounds(); i = 0; while (i < points.length) { bounds.extend(points.getAt(i)); i++; } return map.fitBounds(bounds); }; /* Check if a value is true */ isTrue = function(val) { return angular.isDefined(val) && val !== null && val === true || val === "1" || val === "y" || val === "true"; }; "use strict"; DEFAULTS = {}; return { restrict: "ECA", require: "^googleMap", replace: true, scope: { path: "=path", stroke: "=stroke", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=icons", visible: "=" }, link: function(scope, element, attrs, mapCtrl) { if (angular.isUndefined(scope.path) || scope.path === null || scope.path.length < 2 || !validatePathPoints(scope.path)) { $log.error("polyline: no valid path attribute found"); return; } return $timeout(function() { var map, opts, pathInsertAtListener, pathPoints, pathRemoveAtListener, pathSetAtListener, polyPath, polyline; map = mapCtrl.getMap(); pathPoints = convertPathPoints(scope.path); opts = angular.extend({}, DEFAULTS, { map: map, path: pathPoints, strokeColor: scope.stroke && scope.stroke.color, strokeOpacity: scope.stroke && scope.stroke.opacity, strokeWeight: scope.stroke && scope.stroke.weight }); angular.forEach({ clickable: true, draggable: false, editable: false, geodesic: false, visible: true }, function(defaultValue, key) { if (angular.isUndefined(scope[key]) || scope[key] === null) { return opts[key] = defaultValue; } else { return opts[key] = scope[key]; } }); polyline = new google.maps.Polyline(opts); if (isTrue(attrs.fit)) { extendMapBounds(map, pathPoints); } if (angular.isDefined(scope.editable)) { scope.$watch("editable", function(newValue, oldValue) { return polyline.setEditable(newValue); }); } if (angular.isDefined(scope.draggable)) { scope.$watch("draggable", function(newValue, oldValue) { return polyline.setDraggable(newValue); }); } if (angular.isDefined(scope.visible)) { scope.$watch("visible", function(newValue, oldValue) { return polyline.setVisible(newValue); }); } pathSetAtListener = void 0; pathInsertAtListener = void 0; pathRemoveAtListener = void 0; polyPath = polyline.getPath(); pathSetAtListener = google.maps.event.addListener(polyPath, "set_at", function(index) { var value; value = polyPath.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } scope.path[index].latitude = value.lat(); scope.path[index].longitude = value.lng(); return scope.$apply(); }); pathInsertAtListener = google.maps.event.addListener(polyPath, "insert_at", function(index) { var value; value = polyPath.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } scope.path.splice(index, 0, { latitude: value.lat(), longitude: value.lng() }); return scope.$apply(); }); pathRemoveAtListener = google.maps.event.addListener(polyPath, "remove_at", function(index) { scope.path.splice(index, 1); return scope.$apply(); }); scope.$watch("path", (function(newArray) { var i, l, newLength, newValue, oldArray, oldLength, oldValue; oldArray = polyline.getPath(); if (newArray !== oldArray) { if (newArray) { polyline.setMap(map); i = 0; oldLength = oldArray.getLength(); newLength = newArray.length; l = Math.min(oldLength, newLength); while (i < l) { oldValue = oldArray.getAt(i); newValue = newArray[i]; if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) { oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude)); } i++; } while (i < newLength) { newValue = newArray[i]; oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude)); i++; } while (i < oldLength) { oldArray.pop(); i++; } if (isTrue(attrs.fit)) { return extendMapBounds(map, oldArray); } } else { return polyline.setMap(null); } } }), true); return scope.$on("$destroy", function() { polyline.setMap(null); pathSetAtListener(); pathSetAtListener = null; pathInsertAtListener(); pathInsertAtListener = null; pathRemoveAtListener(); return pathRemoveAtListener = null; }); }); } }; } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module("google-maps").directive("polyline", [ "$log", "$timeout", "array-sync", function($log, $timeout, arraySync) { var DEFAULTS, convertPathPoints, extendMapBounds, isTrue, validatePathPoints; validatePathPoints = function(path) { var i; i = 0; while (i < path.length) { if (angular.isUndefined(path[i].latitude) || angular.isUndefined(path[i].longitude)) { return false; } i++; } return true; }; convertPathPoints = function(path) { var i, result; result = new google.maps.MVCArray(); i = 0; while (i < path.length) { result.push(new google.maps.LatLng(path[i].latitude, path[i].longitude)); i++; } return result; }; extendMapBounds = function(map, points) { var bounds, i; bounds = new google.maps.LatLngBounds(); i = 0; while (i < points.length) { bounds.extend(points.getAt(i)); i++; } return map.fitBounds(bounds); }; /* Check if a value is true */ isTrue = function(val) { return angular.isDefined(val) && val !== null && val === true || val === "1" || val === "y" || val === "true"; }; "use strict"; DEFAULTS = {}; return { restrict: "ECA", replace: true, require: "^googleMap", scope: { path: "=path", stroke: "=stroke", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=icons", visible: "=" }, link: function(scope, element, attrs, mapCtrl) { if (angular.isUndefined(scope.path) || scope.path === null || scope.path.length < 2 || !validatePathPoints(scope.path)) { $log.error("polyline: no valid path attribute found"); return; } return $timeout(function() { var arraySyncer, buildOpts, map, polyline; buildOpts = function(pathPoints) { var opts; opts = angular.extend({}, DEFAULTS, { map: map, path: pathPoints, strokeColor: scope.stroke && scope.stroke.color, strokeOpacity: scope.stroke && scope.stroke.opacity, strokeWeight: scope.stroke && scope.stroke.weight }); angular.forEach({ clickable: true, draggable: false, editable: false, geodesic: false, visible: true }, function(defaultValue, key) { if (angular.isUndefined(scope[key]) || scope[key] === null) { return opts[key] = defaultValue; } else { return opts[key] = scope[key]; } }); return opts; }; map = mapCtrl.getMap(); polyline = new google.maps.Polyline(buildOpts(convertPathPoints(scope.path))); if (isTrue(attrs.fit)) { extendMapBounds(map, pathPoints); } if (angular.isDefined(scope.editable)) { scope.$watch("editable", function(newValue, oldValue) { return polyline.setEditable(newValue); }); } if (angular.isDefined(scope.draggable)) { scope.$watch("draggable", function(newValue, oldValue) { return polyline.setDraggable(newValue); }); } if (angular.isDefined(scope.visible)) { scope.$watch("visible", function(newValue, oldValue) { return polyline.setVisible(newValue); }); } if (angular.isDefined(scope.geodesic)) { scope.$watch("geodesic", function(newValue, oldValue) { return polyline.setOptions(buildOpts(polyline.getPath())); }); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.weight)) { scope.$watch("stroke.weight", function(newValue, oldValue) { return polyline.setOptions(buildOpts(polyline.getPath())); }); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.color)) { scope.$watch("stroke.color", function(newValue, oldValue) { return polyline.setOptions(buildOpts(polyline.getPath())); }); } arraySyncer = arraySync(polyline.getPath(), scope, "path"); return scope.$on("$destroy", function() { polyline.setMap(null); if (arraySyncer) { arraySyncer(); return arraySyncer = null; } }); }); } }; } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map info window directive This directive is used to create an info window on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute show optional} map will show when this expression returns true */ (function() { angular.module("google-maps").directive("window", [ "$timeout", "$compile", "$http", "$templateCache", function($timeout, $compile, $http, $templateCache) { return new directives.api.Window($timeout, $compile, $http, $templateCache); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map info window directive This directive is used to create an info window on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute show optional} map will show when this expression returns true */ (function() { angular.module("google-maps").directive("windows", [ "$timeout", "$compile", "$http", "$templateCache", "$interpolate", function($timeout, $compile, $http, $templateCache, $interpolate) { return new directives.api.Windows($timeout, $compile, $http, $templateCache, $interpolate); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors: - Nicolas Laplante https://plus.google.com/108189012221374960701 - Nicholas McCready - https://twitter.com/nmccready */ /* Map Layer directive This directive is used to create any type of Layer from the google maps sdk. This directive creates a new scope. {attribute show optional} true (default) shows the trafficlayer otherwise it is hidden */ (function() { angular.module("google-maps").directive("layer", [ "$timeout", function($timeout) { return new directives.api.Layer($timeout); } ]); }).call(this); ;/** * @name MarkerClustererPlus for Google Maps V3 * @version 2.1.1 [November 4, 2013] * @author Gary Little * @fileoverview * The library creates and manages per-zoom-level clusters for large amounts of markers. * <p> * This is an enhanced V3 implementation of the * <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/" * >V2 MarkerClusterer</a> by Xiaoxi Wu. It is based on the * <a href="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/" * >V3 MarkerClusterer</a> port by Luke Mahe. MarkerClustererPlus was created by Gary Little. * <p> * v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It * adds support for the <code>ignoreHidden</code>, <code>title</code>, <code>batchSizeIE</code>, * and <code>calculator</code> properties as well as support for four more events. It also allows * greater control over the styling of the text that appears on the cluster marker. The * documentation has been significantly improved and the overall code has been simplified and * polished. Very large numbers of markers can now be managed without causing Javascript timeout * errors on Internet Explorer. Note that the name of the <code>clusterclick</code> event has been * deprecated. The new name is <code>click</code>, so please change your application code now. */ /** * 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. */ /** * @name ClusterIconStyle * @class This class represents the object for values in the <code>styles</code> array passed * to the {@link MarkerClusterer} constructor. The element in this array that is used to * style the cluster icon is determined by calling the <code>calculator</code> function. * * @property {string} url The URL of the cluster icon image file. Required. * @property {number} height The display height (in pixels) of the cluster icon. Required. * @property {number} width The display width (in pixels) of the cluster icon. Required. * @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to * where the text label is to be centered and drawn. The format is <code>[yoffset, xoffset]</code> * where <code>yoffset</code> increases as you go down from center and <code>xoffset</code> * increases to the right of center. The default is <code>[0, 0]</code>. * @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the * spot on the cluster icon that is to be aligned with the cluster position. The format is * <code>[yoffset, xoffset]</code> where <code>yoffset</code> increases as you go down and * <code>xoffset</code> increases to the right of the top-left corner of the icon. The default * anchor position is the center of the cluster icon. * @property {string} [textColor="black"] The color of the label text shown on the * cluster icon. * @property {number} [textSize=11] The size (in pixels) of the label text shown on the * cluster icon. * @property {string} [textDecoration="none"] The value of the CSS <code>text-decoration</code> * property for the label text shown on the cluster icon. * @property {string} [fontWeight="bold"] The value of the CSS <code>font-weight</code> * property for the label text shown on the cluster icon. * @property {string} [fontStyle="normal"] The value of the CSS <code>font-style</code> * property for the label text shown on the cluster icon. * @property {string} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code> * property for the label text shown on the cluster icon. * @property {string} [backgroundPosition="0 0"] The position of the cluster icon image * within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code> * (the same format as for the CSS <code>background-position</code> property). You must set * this property appropriately when the image defined by <code>url</code> represents a sprite * containing multiple images. Note that the position <i>must</i> be specified in px units. */ /** * @name ClusterIconInfo * @class This class is an object containing general information about a cluster icon. This is * the object that a <code>calculator</code> function returns. * * @property {string} text The text of the label to be shown on the cluster icon. * @property {number} index The index plus 1 of the element in the <code>styles</code> * array to be used to style the cluster icon. * @property {string} title The tooltip to display when the mouse moves over the cluster icon. * If this value is <code>undefined</code> or <code>""</code>, <code>title</code> is set to the * value of the <code>title</code> property passed to the MarkerClusterer. */ /** * A cluster icon. * * @constructor * @extends google.maps.OverlayView * @param {Cluster} cluster The cluster with which the icon is to be associated. * @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons * to use for various cluster sizes. * @private */ function ClusterIcon(cluster, styles) { cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView); this.cluster_ = cluster; this.className_ = cluster.getMarkerClusterer().getClusterClass(); this.styles_ = styles; this.center_ = null; this.div_ = null; this.sums_ = null; this.visible_ = false; this.setMap(cluster.getMap()); // Note: this causes onAdd to be called } /** * Adds the icon to the DOM. */ ClusterIcon.prototype.onAdd = function () { var cClusterIcon = this; var cMouseDownInCluster; var cDraggingMapByCluster; this.div_ = document.createElement("div"); this.div_.className = this.className_; if (this.visible_) { this.show(); } this.getPanes().overlayMouseTarget.appendChild(this.div_); // Fix for Issue 157 this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), "bounds_changed", function () { cDraggingMapByCluster = cMouseDownInCluster; }); google.maps.event.addDomListener(this.div_, "mousedown", function () { cMouseDownInCluster = true; cDraggingMapByCluster = false; }); google.maps.event.addDomListener(this.div_, "click", function (e) { cMouseDownInCluster = false; if (!cDraggingMapByCluster) { var theBounds; var mz; var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when a cluster marker is clicked. * @name MarkerClusterer#click * @param {Cluster} c The cluster that was clicked. * @event */ google.maps.event.trigger(mc, "click", cClusterIcon.cluster_); google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name // The default click handler follows. Disable it by setting // the zoomOnClick property to false. if (mc.getZoomOnClick()) { // Zoom into the cluster. mz = mc.getMaxZoom(); theBounds = cClusterIcon.cluster_.getBounds(); mc.getMap().fitBounds(theBounds); // There is a fix for Issue 170 here: setTimeout(function () { mc.getMap().fitBounds(theBounds); // Don't zoom beyond the max zoom level if (mz !== null && (mc.getMap().getZoom() > mz)) { mc.getMap().setZoom(mz + 1); } }, 100); } // Prevent event propagation to the map: e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } } }); google.maps.event.addDomListener(this.div_, "mouseover", function () { var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when the mouse moves over a cluster marker. * @name MarkerClusterer#mouseover * @param {Cluster} c The cluster that the mouse moved over. * @event */ google.maps.event.trigger(mc, "mouseover", cClusterIcon.cluster_); }); google.maps.event.addDomListener(this.div_, "mouseout", function () { var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when the mouse moves out of a cluster marker. * @name MarkerClusterer#mouseout * @param {Cluster} c The cluster that the mouse moved out of. * @event */ google.maps.event.trigger(mc, "mouseout", cClusterIcon.cluster_); }); }; /** * Removes the icon from the DOM. */ ClusterIcon.prototype.onRemove = function () { if (this.div_ && this.div_.parentNode) { this.hide(); google.maps.event.removeListener(this.boundsChangedListener_); google.maps.event.clearInstanceListeners(this.div_); this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /** * Draws the icon. */ ClusterIcon.prototype.draw = function () { if (this.visible_) { var pos = this.getPosFromLatLng_(this.center_); this.div_.style.top = pos.y + "px"; this.div_.style.left = pos.x + "px"; } }; /** * Hides the icon. */ ClusterIcon.prototype.hide = function () { if (this.div_) { this.div_.style.display = "none"; } this.visible_ = false; }; /** * Positions and shows the icon. */ ClusterIcon.prototype.show = function () { if (this.div_) { var img = ""; // NOTE: values must be specified in px units var bp = this.backgroundPosition_.split(" "); var spriteH = parseInt(bp[0].trim(), 10); var spriteV = parseInt(bp[1].trim(), 10); var pos = this.getPosFromLatLng_(this.center_); this.div_.style.cssText = this.createCss(pos); img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; "; if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) { img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " + ((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);"; } img += "'>"; this.div_.innerHTML = img + "<div style='" + "position: absolute;" + "top: " + this.anchorText_[0] + "px;" + "left: " + this.anchorText_[1] + "px;" + "color: " + this.textColor_ + ";" + "font-size: " + this.textSize_ + "px;" + "font-family: " + this.fontFamily_ + ";" + "font-weight: " + this.fontWeight_ + ";" + "font-style: " + this.fontStyle_ + ";" + "text-decoration: " + this.textDecoration_ + ";" + "text-align: center;" + "width: " + this.width_ + "px;" + "line-height:" + this.height_ + "px;" + "'>" + this.sums_.text + "</div>"; if (typeof this.sums_.title === "undefined" || this.sums_.title === "") { this.div_.title = this.cluster_.getMarkerClusterer().getTitle(); } else { this.div_.title = this.sums_.title; } this.div_.style.display = ""; } this.visible_ = true; }; /** * Sets the icon styles to the appropriate element in the styles array. * * @param {ClusterIconInfo} sums The icon label text and styles index. */ ClusterIcon.prototype.useStyle = function (sums) { this.sums_ = sums; var index = Math.max(0, sums.index - 1); index = Math.min(this.styles_.length - 1, index); var style = this.styles_[index]; this.url_ = style.url; this.height_ = style.height; this.width_ = style.width; this.anchorText_ = style.anchorText || [0, 0]; this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)]; this.textColor_ = style.textColor || "black"; this.textSize_ = style.textSize || 11; this.textDecoration_ = style.textDecoration || "none"; this.fontWeight_ = style.fontWeight || "bold"; this.fontStyle_ = style.fontStyle || "normal"; this.fontFamily_ = style.fontFamily || "Arial,sans-serif"; this.backgroundPosition_ = style.backgroundPosition || "0 0"; }; /** * Sets the position at which to center the icon. * * @param {google.maps.LatLng} center The latlng to set as the center. */ ClusterIcon.prototype.setCenter = function (center) { this.center_ = center; }; /** * Creates the cssText style parameter based on the position of the icon. * * @param {google.maps.Point} pos The position of the icon. * @return {string} The CSS style text. */ ClusterIcon.prototype.createCss = function (pos) { var style = []; style.push("cursor: pointer;"); style.push("position: absolute; top: " + pos.y + "px; left: " + pos.x + "px;"); style.push("width: " + this.width_ + "px; height: " + this.height_ + "px;"); return style.join(""); }; /** * Returns the position at which to place the DIV depending on the latlng. * * @param {google.maps.LatLng} latlng The position in latlng. * @return {google.maps.Point} The position in pixels. */ ClusterIcon.prototype.getPosFromLatLng_ = function (latlng) { var pos = this.getProjection().fromLatLngToDivPixel(latlng); pos.x -= this.anchorIcon_[1]; pos.y -= this.anchorIcon_[0]; pos.x = parseInt(pos.x, 10); pos.y = parseInt(pos.y, 10); return pos; }; /** * Creates a single cluster that manages a group of proximate markers. * Used internally, do not call this constructor directly. * @constructor * @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this * cluster is associated. */ function Cluster(mc) { this.markerClusterer_ = mc; this.map_ = mc.getMap(); this.gridSize_ = mc.getGridSize(); this.minClusterSize_ = mc.getMinimumClusterSize(); this.averageCenter_ = mc.getAverageCenter(); this.markers_ = []; this.center_ = null; this.bounds_ = null; this.clusterIcon_ = new ClusterIcon(this, mc.getStyles()); } /** * Returns the number of markers managed by the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {number} The number of markers in the cluster. */ Cluster.prototype.getSize = function () { return this.markers_.length; }; /** * Returns the array of markers managed by the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {Array} The array of markers in the cluster. */ Cluster.prototype.getMarkers = function () { return this.markers_; }; /** * Returns the center of the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {google.maps.LatLng} The center of the cluster. */ Cluster.prototype.getCenter = function () { return this.center_; }; /** * Returns the map with which the cluster is associated. * * @return {google.maps.Map} The map. * @ignore */ Cluster.prototype.getMap = function () { return this.map_; }; /** * Returns the <code>MarkerClusterer</code> object with which the cluster is associated. * * @return {MarkerClusterer} The associated marker clusterer. * @ignore */ Cluster.prototype.getMarkerClusterer = function () { return this.markerClusterer_; }; /** * Returns the bounds of the cluster. * * @return {google.maps.LatLngBounds} the cluster bounds. * @ignore */ Cluster.prototype.getBounds = function () { var i; var bounds = new google.maps.LatLngBounds(this.center_, this.center_); var markers = this.getMarkers(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } return bounds; }; /** * Removes the cluster from the map. * * @ignore */ Cluster.prototype.remove = function () { this.clusterIcon_.setMap(null); this.markers_ = []; delete this.markers_; }; /** * Adds a marker to the cluster. * * @param {google.maps.Marker} marker The marker to be added. * @return {boolean} True if the marker was added. * @ignore */ Cluster.prototype.addMarker = function (marker) { var i; var mCount; var mz; if (this.isMarkerAlreadyAdded_(marker)) { return false; } if (!this.center_) { this.center_ = marker.getPosition(); this.calculateBounds_(); } else { if (this.averageCenter_) { var l = this.markers_.length + 1; var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l; var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l; this.center_ = new google.maps.LatLng(lat, lng); this.calculateBounds_(); } } marker.isAdded = true; this.markers_.push(marker); mCount = this.markers_.length; mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { // Zoomed in past max zoom, so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount < this.minClusterSize_) { // Min cluster size not reached so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount === this.minClusterSize_) { // Hide the markers that were showing. for (i = 0; i < mCount; i++) { this.markers_[i].setMap(null); } } else { marker.setMap(null); } this.updateIcon_(); return true; }; /** * Determines if a marker lies within the cluster's bounds. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker lies in the bounds. * @ignore */ Cluster.prototype.isMarkerInClusterBounds = function (marker) { return this.bounds_.contains(marker.getPosition()); }; /** * Calculates the extended bounds of the cluster with the grid. */ Cluster.prototype.calculateBounds_ = function () { var bounds = new google.maps.LatLngBounds(this.center_, this.center_); this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds); }; /** * Updates the cluster icon. */ Cluster.prototype.updateIcon_ = function () { var mCount = this.markers_.length; var mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { this.clusterIcon_.hide(); return; } if (mCount < this.minClusterSize_) { // Min cluster size not yet reached. this.clusterIcon_.hide(); return; } var numStyles = this.markerClusterer_.getStyles().length; var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles); this.clusterIcon_.setCenter(this.center_); this.clusterIcon_.useStyle(sums); this.clusterIcon_.show(); }; /** * Determines if a marker has already been added to the cluster. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker has already been added. */ Cluster.prototype.isMarkerAlreadyAdded_ = function (marker) { var i; if (this.markers_.indexOf) { return this.markers_.indexOf(marker) !== -1; } else { for (i = 0; i < this.markers_.length; i++) { if (marker === this.markers_[i]) { return true; } } } return false; }; /** * @name MarkerClustererOptions * @class This class represents the optional parameter passed to * the {@link MarkerClusterer} constructor. * @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square. * @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or * <code>null</code> if clustering is to be enabled at all zoom levels. * @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is * clicked. You may want to set this to <code>false</code> if you have installed a handler * for the <code>click</code> event and it deals with zooming on its own. * @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be * the average position of all markers in the cluster. If set to <code>false</code>, the * cluster marker is positioned at the location of the first marker added to the cluster. * @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster * before the markers are hidden and a cluster marker appears. * @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You * may want to set this to <code>true</code> to ensure that hidden markers are not included * in the marker count that appears on a cluster marker (this count is the value of the * <code>text</code> property of the result returned by the default <code>calculator</code>). * If set to <code>true</code> and you change the visibility of a marker being clustered, be * sure to also call <code>MarkerClusterer.repaint()</code>. * @property {string} [title=""] The tooltip to display when the mouse moves over a cluster * marker. (Alternatively, you can use a custom <code>calculator</code> function to specify a * different tooltip for each cluster marker.) * @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine * the text to be displayed on a cluster marker and the index indicating which style to use * for the cluster marker. The input parameters for the function are (1) the array of markers * represented by a cluster marker and (2) the number of cluster icon styles. It returns a * {@link ClusterIconInfo} object. The default <code>calculator</code> returns a * <code>text</code> property which is the number of markers in the cluster and an * <code>index</code> property which is one higher than the lowest integer such that * <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles * array, whichever is less. The <code>styles</code> array element used has an index of * <code>index</code> minus 1. For example, the default <code>calculator</code> returns a * <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code> * for a cluster icon representing 125 markers so the element used in the <code>styles</code> * array is <code>2</code>. A <code>calculator</code> may also return a <code>title</code> * property that contains the text of the tooltip to be used for the cluster marker. If * <code>title</code> is not defined, the tooltip is set to the value of the <code>title</code> * property for the MarkerClusterer. * @property {string} [clusterClass="cluster"] The name of the CSS class defining general styles * for the cluster markers. Use this class to define CSS styles that are not set up by the code * that processes the <code>styles</code> array. * @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles * of the cluster markers to be used. The element to be used to style a given cluster marker * is determined by the function defined by the <code>calculator</code> property. * The default is an array of {@link ClusterIconStyle} elements whose properties are derived * from the values for <code>imagePath</code>, <code>imageExtension</code>, and * <code>imageSizes</code>. * @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that * have sizes that are some multiple (typically double) of their actual display size. Icons such * as these look better when viewed on high-resolution monitors such as Apple's Retina displays. * Note: if this property is <code>true</code>, sprites cannot be used as cluster icons. * @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the * number of markers to be processed in a single batch when using a browser other than * Internet Explorer (for Internet Explorer, use the batchSizeIE property instead). * @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is * being used, markers are processed in several batches with a small delay inserted between * each batch in an attempt to avoid Javascript timeout errors. Set this property to the * number of markers to be processed in a single batch; select as high a number as you can * without causing a timeout error in the browser. This number might need to be as low as 100 * if 15,000 markers are being managed, for example. * @property {string} [imagePath=MarkerClusterer.IMAGE_PATH] * The full URL of the root name of the group of image files to use for cluster icons. * The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code> * where n is the image file number (1, 2, etc.). * @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION] * The extension name for the cluster icon image files (e.g., <code>"png"</code> or * <code>"jpg"</code>). * @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES] * An array of numbers containing the widths of the group of * <code>imagePath</code>n.<code>imageExtension</code> image files. * (The images are assumed to be square.) */ /** * Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}. * @constructor * @extends google.maps.OverlayView * @param {google.maps.Map} map The Google map to attach to. * @param {Array.<google.maps.Marker>} [opt_markers] The markers to be added to the cluster. * @param {MarkerClustererOptions} [opt_options] The optional parameters. */ function MarkerClusterer(map, opt_markers, opt_options) { // MarkerClusterer implements google.maps.OverlayView interface. We use the // extend function to extend MarkerClusterer with google.maps.OverlayView // because it might not always be available when the code is defined so we // look for it at the last possible moment. If it doesn't exist now then // there is no point going ahead :) this.extend(MarkerClusterer, google.maps.OverlayView); opt_markers = opt_markers || []; opt_options = opt_options || {}; this.markers_ = []; this.clusters_ = []; this.listeners_ = []; this.activeMap_ = null; this.ready_ = false; this.gridSize_ = opt_options.gridSize || 60; this.minClusterSize_ = opt_options.minimumClusterSize || 2; this.maxZoom_ = opt_options.maxZoom || null; this.styles_ = opt_options.styles || []; this.title_ = opt_options.title || ""; this.zoomOnClick_ = true; if (opt_options.zoomOnClick !== undefined) { this.zoomOnClick_ = opt_options.zoomOnClick; } this.averageCenter_ = false; if (opt_options.averageCenter !== undefined) { this.averageCenter_ = opt_options.averageCenter; } this.ignoreHidden_ = false; if (opt_options.ignoreHidden !== undefined) { this.ignoreHidden_ = opt_options.ignoreHidden; } this.enableRetinaIcons_ = false; if (opt_options.enableRetinaIcons !== undefined) { this.enableRetinaIcons_ = opt_options.enableRetinaIcons; } this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH; this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION; this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES; this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR; this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE; this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE; this.clusterClass_ = opt_options.clusterClass || "cluster"; if (navigator.userAgent.toLowerCase().indexOf("msie") !== -1) { // Try to avoid IE timeout when processing a huge number of markers: this.batchSize_ = this.batchSizeIE_; } this.setupStyles_(); this.addMarkers(opt_markers, true); this.setMap(map); // Note: this causes onAdd to be called } /** * Implementation of the onAdd interface method. * @ignore */ MarkerClusterer.prototype.onAdd = function () { var cMarkerClusterer = this; this.activeMap_ = this.getMap(); this.ready_ = true; this.repaint(); // Add the map event listeners this.listeners_ = [ google.maps.event.addListener(this.getMap(), "zoom_changed", function () { cMarkerClusterer.resetViewport_(false); // Workaround for this Google bug: when map is at level 0 and "-" of // zoom slider is clicked, a "zoom_changed" event is fired even though // the map doesn't zoom out any further. In this situation, no "idle" // event is triggered so the cluster markers that have been removed // do not get redrawn. Same goes for a zoom in at maxZoom. if (this.getZoom() === (this.get("minZoom") || 0) || this.getZoom() === this.get("maxZoom")) { google.maps.event.trigger(this, "idle"); } }), google.maps.event.addListener(this.getMap(), "idle", function () { cMarkerClusterer.redraw_(); }) ]; }; /** * Implementation of the onRemove interface method. * Removes map event listeners and all cluster icons from the DOM. * All managed markers are also put back on the map. * @ignore */ MarkerClusterer.prototype.onRemove = function () { var i; // Put all the managed markers back on the map: for (i = 0; i < this.markers_.length; i++) { if (this.markers_[i].getMap() !== this.activeMap_) { this.markers_[i].setMap(this.activeMap_); } } // Remove all clusters: for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Remove map event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } this.listeners_ = []; this.activeMap_ = null; this.ready_ = false; }; /** * Implementation of the draw interface method. * @ignore */ MarkerClusterer.prototype.draw = function () {}; /** * Sets up the styles object. */ MarkerClusterer.prototype.setupStyles_ = function () { var i, size; if (this.styles_.length > 0) { return; } for (i = 0; i < this.imageSizes_.length; i++) { size = this.imageSizes_[i]; this.styles_.push({ url: this.imagePath_ + (i + 1) + "." + this.imageExtension_, height: size, width: size }); } }; /** * Fits the map to the bounds of the markers managed by the clusterer. */ MarkerClusterer.prototype.fitMapToMarkers = function () { var i; var markers = this.getMarkers(); var bounds = new google.maps.LatLngBounds(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } this.getMap().fitBounds(bounds); }; /** * Returns the value of the <code>gridSize</code> property. * * @return {number} The grid size. */ MarkerClusterer.prototype.getGridSize = function () { return this.gridSize_; }; /** * Sets the value of the <code>gridSize</code> property. * * @param {number} gridSize The grid size. */ MarkerClusterer.prototype.setGridSize = function (gridSize) { this.gridSize_ = gridSize; }; /** * Returns the value of the <code>minimumClusterSize</code> property. * * @return {number} The minimum cluster size. */ MarkerClusterer.prototype.getMinimumClusterSize = function () { return this.minClusterSize_; }; /** * Sets the value of the <code>minimumClusterSize</code> property. * * @param {number} minimumClusterSize The minimum cluster size. */ MarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) { this.minClusterSize_ = minimumClusterSize; }; /** * Returns the value of the <code>maxZoom</code> property. * * @return {number} The maximum zoom level. */ MarkerClusterer.prototype.getMaxZoom = function () { return this.maxZoom_; }; /** * Sets the value of the <code>maxZoom</code> property. * * @param {number} maxZoom The maximum zoom level. */ MarkerClusterer.prototype.setMaxZoom = function (maxZoom) { this.maxZoom_ = maxZoom; }; /** * Returns the value of the <code>styles</code> property. * * @return {Array} The array of styles defining the cluster markers to be used. */ MarkerClusterer.prototype.getStyles = function () { return this.styles_; }; /** * Sets the value of the <code>styles</code> property. * * @param {Array.<ClusterIconStyle>} styles The array of styles to use. */ MarkerClusterer.prototype.setStyles = function (styles) { this.styles_ = styles; }; /** * Returns the value of the <code>title</code> property. * * @return {string} The content of the title text. */ MarkerClusterer.prototype.getTitle = function () { return this.title_; }; /** * Sets the value of the <code>title</code> property. * * @param {string} title The value of the title property. */ MarkerClusterer.prototype.setTitle = function (title) { this.title_ = title; }; /** * Returns the value of the <code>zoomOnClick</code> property. * * @return {boolean} True if zoomOnClick property is set. */ MarkerClusterer.prototype.getZoomOnClick = function () { return this.zoomOnClick_; }; /** * Sets the value of the <code>zoomOnClick</code> property. * * @param {boolean} zoomOnClick The value of the zoomOnClick property. */ MarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) { this.zoomOnClick_ = zoomOnClick; }; /** * Returns the value of the <code>averageCenter</code> property. * * @return {boolean} True if averageCenter property is set. */ MarkerClusterer.prototype.getAverageCenter = function () { return this.averageCenter_; }; /** * Sets the value of the <code>averageCenter</code> property. * * @param {boolean} averageCenter The value of the averageCenter property. */ MarkerClusterer.prototype.setAverageCenter = function (averageCenter) { this.averageCenter_ = averageCenter; }; /** * Returns the value of the <code>ignoreHidden</code> property. * * @return {boolean} True if ignoreHidden property is set. */ MarkerClusterer.prototype.getIgnoreHidden = function () { return this.ignoreHidden_; }; /** * Sets the value of the <code>ignoreHidden</code> property. * * @param {boolean} ignoreHidden The value of the ignoreHidden property. */ MarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) { this.ignoreHidden_ = ignoreHidden; }; /** * Returns the value of the <code>enableRetinaIcons</code> property. * * @return {boolean} True if enableRetinaIcons property is set. */ MarkerClusterer.prototype.getEnableRetinaIcons = function () { return this.enableRetinaIcons_; }; /** * Sets the value of the <code>enableRetinaIcons</code> property. * * @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property. */ MarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) { this.enableRetinaIcons_ = enableRetinaIcons; }; /** * Returns the value of the <code>imageExtension</code> property. * * @return {string} The value of the imageExtension property. */ MarkerClusterer.prototype.getImageExtension = function () { return this.imageExtension_; }; /** * Sets the value of the <code>imageExtension</code> property. * * @param {string} imageExtension The value of the imageExtension property. */ MarkerClusterer.prototype.setImageExtension = function (imageExtension) { this.imageExtension_ = imageExtension; }; /** * Returns the value of the <code>imagePath</code> property. * * @return {string} The value of the imagePath property. */ MarkerClusterer.prototype.getImagePath = function () { return this.imagePath_; }; /** * Sets the value of the <code>imagePath</code> property. * * @param {string} imagePath The value of the imagePath property. */ MarkerClusterer.prototype.setImagePath = function (imagePath) { this.imagePath_ = imagePath; }; /** * Returns the value of the <code>imageSizes</code> property. * * @return {Array} The value of the imageSizes property. */ MarkerClusterer.prototype.getImageSizes = function () { return this.imageSizes_; }; /** * Sets the value of the <code>imageSizes</code> property. * * @param {Array} imageSizes The value of the imageSizes property. */ MarkerClusterer.prototype.setImageSizes = function (imageSizes) { this.imageSizes_ = imageSizes; }; /** * Returns the value of the <code>calculator</code> property. * * @return {function} the value of the calculator property. */ MarkerClusterer.prototype.getCalculator = function () { return this.calculator_; }; /** * Sets the value of the <code>calculator</code> property. * * @param {function(Array.<google.maps.Marker>, number)} calculator The value * of the calculator property. */ MarkerClusterer.prototype.setCalculator = function (calculator) { this.calculator_ = calculator; }; /** * Returns the value of the <code>batchSizeIE</code> property. * * @return {number} the value of the batchSizeIE property. */ MarkerClusterer.prototype.getBatchSizeIE = function () { return this.batchSizeIE_; }; /** * Sets the value of the <code>batchSizeIE</code> property. * * @param {number} batchSizeIE The value of the batchSizeIE property. */ MarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) { this.batchSizeIE_ = batchSizeIE; }; /** * Returns the value of the <code>clusterClass</code> property. * * @return {string} the value of the clusterClass property. */ MarkerClusterer.prototype.getClusterClass = function () { return this.clusterClass_; }; /** * Sets the value of the <code>clusterClass</code> property. * * @param {string} clusterClass The value of the clusterClass property. */ MarkerClusterer.prototype.setClusterClass = function (clusterClass) { this.clusterClass_ = clusterClass; }; /** * Returns the array of markers managed by the clusterer. * * @return {Array} The array of markers managed by the clusterer. */ MarkerClusterer.prototype.getMarkers = function () { return this.markers_; }; /** * Returns the number of markers managed by the clusterer. * * @return {number} The number of markers. */ MarkerClusterer.prototype.getTotalMarkers = function () { return this.markers_.length; }; /** * Returns the current array of clusters formed by the clusterer. * * @return {Array} The array of clusters formed by the clusterer. */ MarkerClusterer.prototype.getClusters = function () { return this.clusters_; }; /** * Returns the number of clusters formed by the clusterer. * * @return {number} The number of clusters formed by the clusterer. */ MarkerClusterer.prototype.getTotalClusters = function () { return this.clusters_.length; }; /** * Adds a marker to the clusterer. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. * * @param {google.maps.Marker} marker The marker to add. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. */ MarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) { this.pushMarkerTo_(marker); if (!opt_nodraw) { this.redraw_(); } }; /** * Adds an array of markers to the clusterer. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. * * @param {Array.<google.maps.Marker>} markers The markers to add. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. */ MarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) { var key; for (key in markers) { if (markers.hasOwnProperty(key)) { this.pushMarkerTo_(markers[key]); } } if (!opt_nodraw) { this.redraw_(); } }; /** * Pushes a marker to the clusterer. * * @param {google.maps.Marker} marker The marker to add. */ MarkerClusterer.prototype.pushMarkerTo_ = function (marker) { // If the marker is draggable add a listener so we can update the clusters on the dragend: if (marker.getDraggable()) { var cMarkerClusterer = this; google.maps.event.addListener(marker, "dragend", function () { if (cMarkerClusterer.ready_) { this.isAdded = false; cMarkerClusterer.repaint(); } }); } marker.isAdded = false; this.markers_.push(marker); }; /** * Removes a marker from the cluster. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the * marker was removed from the clusterer. * * @param {google.maps.Marker} marker The marker to remove. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. * @return {boolean} True if the marker was removed from the clusterer. */ MarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) { var removed = this.removeMarker_(marker); if (!opt_nodraw && removed) { this.repaint(); } return removed; }; /** * Removes an array of markers from the cluster. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers * were removed from the clusterer. * * @param {Array.<google.maps.Marker>} markers The markers to remove. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. * @return {boolean} True if markers were removed from the clusterer. */ MarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) { var i, r; var removed = false; for (i = 0; i < markers.length; i++) { r = this.removeMarker_(markers[i]); removed = removed || r; } if (!opt_nodraw && removed) { this.repaint(); } return removed; }; /** * Removes a marker and returns true if removed, false if not. * * @param {google.maps.Marker} marker The marker to remove * @return {boolean} Whether the marker was removed or not */ MarkerClusterer.prototype.removeMarker_ = function (marker) { var i; var index = -1; if (this.markers_.indexOf) { index = this.markers_.indexOf(marker); } else { for (i = 0; i < this.markers_.length; i++) { if (marker === this.markers_[i]) { index = i; break; } } } if (index === -1) { // Marker is not in our list of markers, so do nothing: return false; } marker.setMap(null); this.markers_.splice(index, 1); // Remove the marker from the list of managed markers return true; }; /** * Removes all clusters and markers from the map and also removes all markers * managed by the clusterer. */ MarkerClusterer.prototype.clearMarkers = function () { this.resetViewport_(true); this.markers_ = []; }; /** * Recalculates and redraws all the marker clusters from scratch. * Call this after changing any properties. */ MarkerClusterer.prototype.repaint = function () { var oldClusters = this.clusters_.slice(); this.clusters_ = []; this.resetViewport_(false); this.redraw_(); // Remove the old clusters. // Do it in a timeout to prevent blinking effect. setTimeout(function () { var i; for (i = 0; i < oldClusters.length; i++) { oldClusters[i].remove(); } }, 0); }; /** * Returns the current bounds extended by the grid size. * * @param {google.maps.LatLngBounds} bounds The bounds to extend. * @return {google.maps.LatLngBounds} The extended bounds. * @ignore */ MarkerClusterer.prototype.getExtendedBounds = function (bounds) { var projection = this.getProjection(); // Turn the bounds into latlng. var tr = new google.maps.LatLng(bounds.getNorthEast().lat(), bounds.getNorthEast().lng()); var bl = new google.maps.LatLng(bounds.getSouthWest().lat(), bounds.getSouthWest().lng()); // Convert the points to pixels and the extend out by the grid size. var trPix = projection.fromLatLngToDivPixel(tr); trPix.x += this.gridSize_; trPix.y -= this.gridSize_; var blPix = projection.fromLatLngToDivPixel(bl); blPix.x -= this.gridSize_; blPix.y += this.gridSize_; // Convert the pixel points back to LatLng var ne = projection.fromDivPixelToLatLng(trPix); var sw = projection.fromDivPixelToLatLng(blPix); // Extend the bounds to contain the new bounds. bounds.extend(ne); bounds.extend(sw); return bounds; }; /** * Redraws all the clusters. */ MarkerClusterer.prototype.redraw_ = function () { this.createClusters_(0); }; /** * Removes all clusters from the map. The markers are also removed from the map * if <code>opt_hide</code> is set to <code>true</code>. * * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers * from the map. */ MarkerClusterer.prototype.resetViewport_ = function (opt_hide) { var i, marker; // Remove all the clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Reset the markers to not be added and to be removed from the map. for (i = 0; i < this.markers_.length; i++) { marker = this.markers_[i]; marker.isAdded = false; if (opt_hide) { marker.setMap(null); } } }; /** * Calculates the distance between two latlng locations in km. * * @param {google.maps.LatLng} p1 The first lat lng point. * @param {google.maps.LatLng} p2 The second lat lng point. * @return {number} The distance between the two points in km. * @see http://www.movable-type.co.uk/scripts/latlong.html */ MarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) { var R = 6371; // Radius of the Earth in km var dLat = (p2.lat() - p1.lat()) * Math.PI / 180; var dLon = (p2.lng() - p1.lng()) * Math.PI / 180; var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d; }; /** * Determines if a marker is contained in a bounds. * * @param {google.maps.Marker} marker The marker to check. * @param {google.maps.LatLngBounds} bounds The bounds to check against. * @return {boolean} True if the marker is in the bounds. */ MarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) { return bounds.contains(marker.getPosition()); }; /** * Adds a marker to a cluster, or creates a new cluster. * * @param {google.maps.Marker} marker The marker to add. */ MarkerClusterer.prototype.addToClosestCluster_ = function (marker) { var i, d, cluster, center; var distance = 40000; // Some large number var clusterToAddTo = null; for (i = 0; i < this.clusters_.length; i++) { cluster = this.clusters_[i]; center = cluster.getCenter(); if (center) { d = this.distanceBetweenPoints_(center, marker.getPosition()); if (d < distance) { distance = d; clusterToAddTo = cluster; } } } if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) { clusterToAddTo.addMarker(marker); } else { cluster = new Cluster(this); cluster.addMarker(marker); this.clusters_.push(cluster); } }; /** * Creates the clusters. This is done in batches to avoid timeout errors * in some browsers when there is a huge number of markers. * * @param {number} iFirst The index of the first marker in the batch of * markers to be added to clusters. */ MarkerClusterer.prototype.createClusters_ = function (iFirst) { var i, marker; var mapBounds; var cMarkerClusterer = this; if (!this.ready_) { return; } // Cancel previous batch processing if we're working on the first batch: if (iFirst === 0) { /** * This event is fired when the <code>MarkerClusterer</code> begins * clustering markers. * @name MarkerClusterer#clusteringbegin * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringbegin", this); if (typeof this.timerRefStatic !== "undefined") { clearTimeout(this.timerRefStatic); delete this.timerRefStatic; } } // Get our current map view bounds. // Create a new bounds object so we don't affect the map. // // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug: if (this.getMap().getZoom() > 3) { mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(), this.getMap().getBounds().getNorthEast()); } else { mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625)); } var bounds = this.getExtendedBounds(mapBounds); var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length); for (i = iFirst; i < iLast; i++) { marker = this.markers_[i]; if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) { if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) { this.addToClosestCluster_(marker); } } } if (iLast < this.markers_.length) { this.timerRefStatic = setTimeout(function () { cMarkerClusterer.createClusters_(iLast); }, 0); } else { delete this.timerRefStatic; /** * This event is fired when the <code>MarkerClusterer</code> stops * clustering markers. * @name MarkerClusterer#clusteringend * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringend", this); } }; /** * Extends an object's prototype by another's. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ MarkerClusterer.prototype.extend = function (obj1, obj2) { return (function (object) { var property; for (property in object.prototype) { this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; /** * The default function for determining the label text and style * for a cluster icon. * * @param {Array.<google.maps.Marker>} markers The array of markers represented by the cluster. * @param {number} numStyles The number of marker styles available. * @return {ClusterIconInfo} The information resource for the cluster. * @constant * @ignore */ MarkerClusterer.CALCULATOR = function (markers, numStyles) { var index = 0; var title = ""; var count = markers.length.toString(); var dv = count; while (dv !== 0) { dv = parseInt(dv / 10, 10); index++; } index = Math.min(index, numStyles); return { text: count, index: index, title: title }; }; /** * The number of markers to process in one batch. * * @type {number} * @constant */ MarkerClusterer.BATCH_SIZE = 2000; /** * The number of markers to process in one batch (IE only). * * @type {number} * @constant */ MarkerClusterer.BATCH_SIZE_IE = 500; /** * The default root name for the marker cluster images. * * @type {string} * @constant */ MarkerClusterer.IMAGE_PATH = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m"; /** * The default extension name for the marker cluster images. * * @type {string} * @constant */ MarkerClusterer.IMAGE_EXTENSION = "png"; /** * The default array of sizes for the marker cluster images. * * @type {Array.<number>} * @constant */ MarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90]; if (typeof String.prototype.trim !== 'function') { /** * IE hack since trim() doesn't exist in all browsers * @return {string} The string with removed whitespace */ String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); } } ;/** * 1.1.9-patched * @name MarkerWithLabel for V3 * @version 1.1.8 [February 26, 2013] * @author Gary Little (inspired by code from Marc Ridey of Google). * @copyright Copyright 2012 Gary Little [gary at luxcentral.com] * @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3 * <code>google.maps.Marker</code> class. * <p> * MarkerWithLabel allows you to define markers with associated labels. As you would expect, * if the marker is draggable, so too will be the label. In addition, a marker with a label * responds to all mouse events in the same manner as a regular marker. It also fires mouse * events and "property changed" events just as a regular marker would. Version 1.1 adds * support for the raiseOnDrag feature introduced in API V3.3. * <p> * If you drag a marker by its label, you can cancel the drag and return the marker to its * original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker * itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class. */ /*! * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint browser:true */ /*global document,google */ /** * @param {Function} childCtor Child class. * @param {Function} parentCtor Parent class. */ function inherits(childCtor, parentCtor) { /** @constructor */ function tempCtor() {} tempCtor.prototype = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype; childCtor.prototype = new tempCtor(); /** @override */ childCtor.prototype.constructor = childCtor; } /** * This constructor creates a label and associates it with a marker. * It is for the private use of the MarkerWithLabel class. * @constructor * @param {Marker} marker The marker with which the label is to be associated. * @param {string} crossURL The URL of the cross image =. * @param {string} handCursor The URL of the hand cursor. * @private */ function MarkerLabel_(marker, crossURL, handCursorURL) { this.marker_ = marker; this.handCursorURL_ = marker.handCursorURL; this.labelDiv_ = document.createElement("div"); this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;"; // Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil // in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that // events can be captured even if the label is in the shadow of a google.maps.InfoWindow. // Code is included here to ensure the veil is always exactly the same size as the label. this.eventDiv_ = document.createElement("div"); this.eventDiv_.style.cssText = this.labelDiv_.style.cssText; // This is needed for proper behavior on MSIE: this.eventDiv_.setAttribute("onselectstart", "return false;"); this.eventDiv_.setAttribute("ondragstart", "return false;"); // Get the DIV for the "X" to be displayed when the marker is raised. this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL); } inherits(MarkerLabel_, google.maps.OverlayView); /** * Returns the DIV for the cross used when dragging a marker when the * raiseOnDrag parameter set to true. One cross is shared with all markers. * @param {string} crossURL The URL of the cross image =. * @private */ MarkerLabel_.getSharedCross = function (crossURL) { var div; if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") { div = document.createElement("img"); div.style.cssText = "position: absolute; z-index: 1000002; display: none;"; // Hopefully Google never changes the standard "X" attributes: div.style.marginLeft = "-8px"; div.style.marginTop = "-9px"; div.src = crossURL; MarkerLabel_.getSharedCross.crossDiv = div; } return MarkerLabel_.getSharedCross.crossDiv; }; /** * Adds the DIV representing the label to the DOM. This method is called * automatically when the marker's <code>setMap</code> method is called. * @private */ MarkerLabel_.prototype.onAdd = function () { var me = this; var cMouseIsDown = false; var cDraggingLabel = false; var cSavedZIndex; var cLatOffset, cLngOffset; var cIgnoreClick; var cRaiseEnabled; var cStartPosition; var cStartCenter; // Constants: var cRaiseOffset = 20; var cDraggingCursor = "url(" + this.handCursorURL_ + ")"; // Stops all processing of an event. // var cAbortEvent = function (e) { if (e.preventDefault) { e.preventDefault(); } e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; var cStopBounce = function () { me.marker_.setAnimation(null); }; this.getPanes().overlayImage.appendChild(this.labelDiv_); this.getPanes().overlayMouseTarget.appendChild(this.eventDiv_); // One cross is shared with all markers, so only add it once: if (typeof MarkerLabel_.getSharedCross.processed === "undefined") { this.getPanes().overlayImage.appendChild(this.crossDiv_); MarkerLabel_.getSharedCross.processed = true; } this.listeners_ = [ google.maps.event.addDomListener(this.eventDiv_, "mouseover", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { this.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseover", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mouseout", function (e) { if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) { this.style.cursor = me.marker_.getCursor(); google.maps.event.trigger(me.marker_, "mouseout", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mousedown", function (e) { cDraggingLabel = false; if (me.marker_.getDraggable()) { cMouseIsDown = true; this.style.cursor = cDraggingCursor; } if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "mousedown", e); cAbortEvent(e); // Prevent map pan when starting a drag on a label } }), google.maps.event.addDomListener(document, "mouseup", function (mEvent) { var position; if (cMouseIsDown) { cMouseIsDown = false; me.eventDiv_.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseup", mEvent); } if (cDraggingLabel) { if (cRaiseEnabled) { // Lower the marker & label position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition()); position.y += cRaiseOffset; me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); // This is not the same bouncing style as when the marker portion is dragged, // but it will have to do: try { // Will fail if running Google Maps API earlier than V3.3 me.marker_.setAnimation(google.maps.Animation.BOUNCE); setTimeout(cStopBounce, 1406); } catch (e) {} } me.crossDiv_.style.display = "none"; me.marker_.setZIndex(cSavedZIndex); cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag cDraggingLabel = false; mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragend", mEvent); } }), google.maps.event.addListener(me.marker_.getMap(), "mousemove", function (mEvent) { var position; if (cMouseIsDown) { if (cDraggingLabel) { // Change the reported location from the mouse position to the marker position: mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset); position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng); if (cRaiseEnabled) { me.crossDiv_.style.left = position.x + "px"; me.crossDiv_.style.top = position.y + "px"; me.crossDiv_.style.display = ""; position.y -= cRaiseOffset; } me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly me.eventDiv_.style.top = (position.y + cRaiseOffset) + "px"; } google.maps.event.trigger(me.marker_, "drag", mEvent); } else { // Calculate offsets from the click point to the marker position: cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat(); cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng(); cSavedZIndex = me.marker_.getZIndex(); cStartPosition = me.marker_.getPosition(); cStartCenter = me.marker_.getMap().getCenter(); cRaiseEnabled = me.marker_.get("raiseOnDrag"); cDraggingLabel = true; me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragstart", mEvent); } } }), google.maps.event.addDomListener(document, "keydown", function (e) { if (cDraggingLabel) { if (e.keyCode === 27) { // Esc key cRaiseEnabled = false; me.marker_.setPosition(cStartPosition); me.marker_.getMap().setCenter(cStartCenter); google.maps.event.trigger(document, "mouseup", e); } } }), google.maps.event.addDomListener(this.eventDiv_, "click", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { if (cIgnoreClick) { // Ignore the click reported when a label drag ends cIgnoreClick = false; } else { google.maps.event.trigger(me.marker_, "click", e); cAbortEvent(e); // Prevent click from being passed on to map } } }), google.maps.event.addDomListener(this.eventDiv_, "dblclick", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "dblclick", e); cAbortEvent(e); // Prevent map zoom when double-clicking on a label } }), google.maps.event.addListener(this.marker_, "dragstart", function (mEvent) { if (!cDraggingLabel) { cRaiseEnabled = this.get("raiseOnDrag"); } }), google.maps.event.addListener(this.marker_, "drag", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(cRaiseOffset); // During a drag, the marker's z-index is temporarily set to 1000000 to // ensure it appears above all other markers. Also set the label's z-index // to 1000000 (plus or minus 1 depending on whether the label is supposed // to be above or below the marker). me.labelDiv_.style.zIndex = 1000000 + (this.get("labelInBackground") ? -1 : +1); } } }), google.maps.event.addListener(this.marker_, "dragend", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(0); // Also restores z-index of label } } }), google.maps.event.addListener(this.marker_, "position_changed", function () { me.setPosition(); }), google.maps.event.addListener(this.marker_, "zindex_changed", function () { me.setZIndex(); }), google.maps.event.addListener(this.marker_, "visible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "labelvisible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "title_changed", function () { me.setTitle(); }), google.maps.event.addListener(this.marker_, "labelcontent_changed", function () { me.setContent(); }), google.maps.event.addListener(this.marker_, "labelanchor_changed", function () { me.setAnchor(); }), google.maps.event.addListener(this.marker_, "labelclass_changed", function () { me.setStyles(); }), google.maps.event.addListener(this.marker_, "labelstyle_changed", function () { me.setStyles(); }) ]; }; /** * Removes the DIV for the label from the DOM. It also removes all event handlers. * This method is called automatically when the marker's <code>setMap(null)</code> * method is called. * @private */ MarkerLabel_.prototype.onRemove = function () { var i; if (this.labelDiv_.parentNode !== null) this.labelDiv_.parentNode.removeChild(this.labelDiv_); if (this.eventDiv_.parentNode !== null) this.eventDiv_.parentNode.removeChild(this.eventDiv_); // Remove event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } }; /** * Draws the label on the map. * @private */ MarkerLabel_.prototype.draw = function () { this.setContent(); this.setTitle(); this.setStyles(); }; /** * Sets the content of the label. * The content can be plain text or an HTML DOM node. * @private */ MarkerLabel_.prototype.setContent = function () { var content = this.marker_.get("labelContent"); if (typeof content.nodeType === "undefined") { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; } else { this.labelDiv_.innerHTML = ""; // Remove current content this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.eventDiv_.appendChild(content); } }; /** * Sets the content of the tool tip for the label. It is * always set to be the same as for the marker itself. * @private */ MarkerLabel_.prototype.setTitle = function () { this.eventDiv_.title = this.marker_.getTitle() || ""; }; /** * Sets the style of the label by setting the style sheet and applying * other specific styles requested. * @private */ MarkerLabel_.prototype.setStyles = function () { var i, labelStyle; // Apply style values from the style sheet defined in the labelClass parameter: this.labelDiv_.className = this.marker_.get("labelClass"); this.eventDiv_.className = this.labelDiv_.className; // Clear existing inline style values: this.labelDiv_.style.cssText = ""; this.eventDiv_.style.cssText = ""; // Apply style values defined in the labelStyle parameter: labelStyle = this.marker_.get("labelStyle"); for (i in labelStyle) { if (labelStyle.hasOwnProperty(i)) { this.labelDiv_.style[i] = labelStyle[i]; this.eventDiv_.style[i] = labelStyle[i]; } } this.setMandatoryStyles(); }; /** * Sets the mandatory styles to the DIV representing the label as well as to the * associated event DIV. This includes setting the DIV position, z-index, and visibility. * @private */ MarkerLabel_.prototype.setMandatoryStyles = function () { this.labelDiv_.style.position = "absolute"; this.labelDiv_.style.overflow = "hidden"; // Make sure the opacity setting causes the desired effect on MSIE: if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") { this.labelDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")\""; this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")"; } this.eventDiv_.style.position = this.labelDiv_.style.position; this.eventDiv_.style.overflow = this.labelDiv_.style.overflow; this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE this.eventDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\""; this.eventDiv_.style.filter = "alpha(opacity=1)"; // For MSIE this.setAnchor(); this.setPosition(); // This also updates z-index, if necessary. this.setVisible(); }; /** * Sets the anchor point of the label. * @private */ MarkerLabel_.prototype.setAnchor = function () { var anchor = this.marker_.get("labelAnchor"); this.labelDiv_.style.marginLeft = -anchor.x + "px"; this.labelDiv_.style.marginTop = -anchor.y + "px"; this.eventDiv_.style.marginLeft = -anchor.x + "px"; this.eventDiv_.style.marginTop = -anchor.y + "px"; }; /** * Sets the position of the label. The z-index is also updated, if necessary. * @private */ MarkerLabel_.prototype.setPosition = function (yOffset) { var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition()); if (typeof yOffset === "undefined") { yOffset = 0; } this.labelDiv_.style.left = Math.round(position.x) + "px"; this.labelDiv_.style.top = Math.round(position.y - yOffset) + "px"; this.eventDiv_.style.left = this.labelDiv_.style.left; this.eventDiv_.style.top = this.labelDiv_.style.top; this.setZIndex(); }; /** * Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index * of the label is set to the vertical coordinate of the label. This is in keeping with the default * stacking order for Google Maps: markers to the south are in front of markers to the north. * @private */ MarkerLabel_.prototype.setZIndex = function () { var zAdjust = (this.marker_.get("labelInBackground") ? -1 : +1); if (typeof this.marker_.getZIndex() === "undefined") { this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } else { this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } }; /** * Sets the visibility of the label. The label is visible only if the marker itself is * visible (i.e., its visible property is true) and the labelVisible property is true. * @private */ MarkerLabel_.prototype.setVisible = function () { if (this.marker_.get("labelVisible")) { this.labelDiv_.style.display = this.marker_.getVisible() ? "block" : "none"; } else { this.labelDiv_.style.display = "none"; } this.eventDiv_.style.display = this.labelDiv_.style.display; }; /** * @name MarkerWithLabelOptions * @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor. * The properties available are the same as for <code>google.maps.Marker</code> with the addition * of the properties listed below. To change any of these additional properties after the labeled * marker has been created, call <code>google.maps.Marker.set(propertyName, propertyValue)</code>. * <p> * When any of these properties changes, a property changed event is fired. The names of these * events are derived from the name of the property and are of the form <code>propertyname_changed</code>. * For example, if the content of the label changes, a <code>labelcontent_changed</code> event * is fired. * <p> * @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node). * @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so * that its top left corner is positioned at the anchor point of the associated marker. Use this * property to change the anchor point of the label. For example, to center a 50px-wide label * beneath a marker, specify a <code>labelAnchor</code> of <code>google.maps.Point(25, 0)</code>. * (Note: x-values increase to the right and y-values increase to the top.) * @property {string} [labelClass] The name of the CSS class defining the styles for the label. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {Object} [labelStyle] An object literal whose properties define specific CSS * style values to be applied to the label. Style values defined here override those that may * be defined in the <code>labelClass</code> style sheet. If this property is changed after the * label has been created, all previously set styles (except those defined in the style sheet) * are removed from the label before the new style values are applied. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its * associated marker should appear in the background (i.e., in a plane below the marker). * The default is <code>false</code>, which causes the label to appear in the foreground. * @property {boolean} [labelVisible] A flag indicating whether the label is to be visible. * The default is <code>true</code>. Note that even if <code>labelVisible</code> is * <code>true</code>, the label will <i>not</i> be visible unless the associated marker is also * visible (i.e., unless the marker's <code>visible</code> property is <code>true</code>). * @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be * raised when the marker is dragged. The default is <code>true</code>. If a draggable marker is * being created and a version of Google Maps API earlier than V3.3 is being used, this property * must be set to <code>false</code>. * @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the * marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel, * so the value of this parameter is always forced to <code>false</code>. * @property {string} [crossImage="http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"] * The URL of the cross image to be displayed while dragging a marker. * @property {string} [handCursor="http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"] * The URL of the cursor to be displayed while dragging a marker. */ /** * Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}. * @constructor * @param {MarkerWithLabelOptions} [opt_options] The optional parameters. */ function MarkerWithLabel(opt_options) { opt_options = opt_options || {}; opt_options.labelContent = opt_options.labelContent || ""; opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0); opt_options.labelClass = opt_options.labelClass || "markerLabels"; opt_options.labelStyle = opt_options.labelStyle || {}; opt_options.labelInBackground = opt_options.labelInBackground || false; if (typeof opt_options.labelVisible === "undefined") { opt_options.labelVisible = true; } if (typeof opt_options.raiseOnDrag === "undefined") { opt_options.raiseOnDrag = true; } if (typeof opt_options.clickable === "undefined") { opt_options.clickable = true; } if (typeof opt_options.draggable === "undefined") { opt_options.draggable = false; } if (typeof opt_options.optimized === "undefined") { opt_options.optimized = false; } opt_options.crossImage = opt_options.crossImage || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; opt_options.handCursor = opt_options.handCursor || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"; opt_options.optimized = false; // Optimized rendering is not supported this.label = new MarkerLabel_(this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker // Call the parent constructor. It calls Marker.setValues to initialize, so all // the new parameters are conveniently saved and can be accessed with get/set. // Marker.set triggers a property changed event (called "propertyname_changed") // that the marker label listens for in order to react to state changes. google.maps.Marker.apply(this, arguments); } inherits(MarkerWithLabel, google.maps.Marker); /** * Overrides the standard Marker setMap function. * @param {Map} theMap The map to which the marker is to be added. * @private */ MarkerWithLabel.prototype.setMap = function (theMap) { // Call the inherited function... google.maps.Marker.prototype.setMap.apply(this, arguments); // ... then deal with the label: this.label.setMap(theMap); };
src/components/DataPicker/Calender.js
Jguardado/ComponentBase
import React, { Component } from 'react'; import MonthHeader from './MonthHeader'; import WeekHeader from './WeekHeader'; import Weeks, { moveTo } from './Weeks'; // import Weeks from './Weeks'; export default class Calendar extends Component { onMove(view, isForward) { Weeks.prototype.moveTo(view, isForward); } onTransitionEnd() { MonthHeader.prototype.enable(); } render() { console.log("props in Calendar: ", this.props); const outcome = 'calendar' + this.props.visible ? ' visible' : ''; console.log('starting to render'); return ( <div className={outcome}> <MonthHeader view={this.props.view} onMove={this.onMove}/> <WeekHeader /> <Weeks view={this.props.view} selected={ this.props.selected } onTransitionEnd={ this.onTransitionEnd } onSelect={ this.props.onSelect } minDate={ this.props.minDate } maxDate={ this.props.maxDate } /> </div> ); } }
src/components/content/Music/MusicRelatedArtists.js
dreamyguy/sidhree-com
import React from 'react'; import { v4 as uuidv4 } from 'uuid'; import { isNotEmptyArray } from '../../../utils/isEmptyUtil'; import './MusicRelatedArtists.scss'; const renderRelatedArtists = relatedArtists => { const output = []; relatedArtists.map((a, i) => { const separator = () => { let separator = ','; // if (i === relatedArtists.length - 2) { // separator = ' and'; if (i === relatedArtists.length - 1) { separator = ' and other similar artists.'; } return separator; } output.push( <li key={uuidv4()}> <span> <a href={a.artistSpotifyUrl} title={a.artistName} className="no-decor"> {a.artistName} </a> {separator()}&nbsp; </span> </li> ); return null; }) return output; }; const MusicRelatedArtists = ({ relatedArtists, singleName }) => { if (relatedArtists && isNotEmptyArray(relatedArtists)) { return ( <div className="row"> <div className="small-12 columns"> <h2 className="heading-two open-sans-light fg-sb-graylighter gutter-bottom"> '{singleName}' is influenced by and/or similar to:</h2> <ul className="related-artists-list list-inline-block"> {renderRelatedArtists(relatedArtists)} </ul> </div> </div> ); } return null; }; export default MusicRelatedArtists;
js/components/Results/Astronaut.js
jvalen/nth-days-old
import React from 'react'; const Astronaut = () => { return ( <div className="astronaut"> <div className="astronaut__place-wrapper"> <div className="place__img"></div> </div> </div> ); }; export default Astronaut;
App/Containers/RootContainer.js
okmttdhr/YoutuVote
// @flow import React, { Component } from 'react'; import { View, StatusBar } from 'react-native'; import { connect } from 'react-redux'; import NavigationRouter from '../Navigation/NavigationRouter'; import StartupActions from '../Redux/StartupRedux'; import ReduxPersist from '../Config/ReduxPersist'; import styles from './Styles/RootContainerStyle'; class RootContainer extends Component<any, void> { componentDidMount() { if (!ReduxPersist.active) { this.props.startup(); } } props: { startup: () => void; } render() { return ( <View style={styles.applicationView}> <StatusBar barStyle="dark-content" /> <NavigationRouter /> </View> ); } } const mapDispatchToProps = dispatch => ({ startup: () => dispatch(StartupActions.startup()), }); export default connect(null, mapDispatchToProps)(RootContainer);
ajax/libs/legojs/0.0.1/lego.min.js
pcarrier/cdnjs
/* * __ _ * / /__ ____ ____ (_)____ * / / _ \/ __ `/ __ \ / / ___/ * / / __/ /_/ / /_/ / / (__ ) * /_/\___/\__, /\____(_)_/ /____/ * /____/ /___/ * * * https://github.com/tybenz/legojs * * made in 2013 * by * Tyler Benziger * -------------- * http://tybenz.com * http://github.com/tybenz * http://twitter.com/tybenz * * License: https://github.com/tybenz/legojs/blob/master/LICENSE.txt * * */ !function(e,t){"function"==typeof define&&define.amd?define(t):e.Lego=t()}(window,function(){var e,t,n;return function(r){function i(e,t){return x.call(e,t)}function o(e,t){var n,r,i,o,a,s,u,l,c,f,p=t&&t.split("/"),d=v.map,h=d&&d["*"]||{};if(e&&"."===e.charAt(0))if(t){for(p=p.slice(0,p.length-1),e=p.concat(e.split("/")),l=0;l<e.length;l+=1)if(f=e[l],"."===f)e.splice(l,1),l-=1;else if(".."===f){if(1===l&&(".."===e[2]||".."===e[0]))break;l>0&&(e.splice(l-1,2),l-=2)}e=e.join("/")}else 0===e.indexOf("./")&&(e=e.substring(2));if((p||h)&&d){for(n=e.split("/"),l=n.length;l>0;l-=1){if(r=n.slice(0,l).join("/"),p)for(c=p.length;c>0;c-=1)if(i=d[p.slice(0,c).join("/")],i&&(i=i[r])){o=i,a=l;break}if(o)break;!s&&h&&h[r]&&(s=h[r],u=l)}!o&&s&&(o=s,a=u),o&&(n.splice(0,a,o),e=n.join("/"))}return e}function a(e,t){return function(){return d.apply(r,w.call(arguments,0).concat([e,t]))}}function s(e){return function(t){return o(t,e)}}function u(e){return function(t){m[e]=t}}function l(e){if(i(y,e)){var t=y[e];delete y[e],b[e]=!0,p.apply(r,t)}if(!i(m,e)&&!i(b,e))throw new Error("No "+e);return m[e]}function c(e){var t,n=e?e.indexOf("!"):-1;return n>-1&&(t=e.substring(0,n),e=e.substring(n+1,e.length)),[t,e]}function f(e){return function(){return v&&v.config&&v.config[e]||{}}}var p,d,h,g,m={},y={},v={},b={},x=Object.prototype.hasOwnProperty,w=[].slice;h=function(e,t){var n,r=c(e),i=r[0];return e=r[1],i&&(i=o(i,t),n=l(i)),i?e=n&&n.normalize?n.normalize(e,s(t)):o(e,t):(e=o(e,t),r=c(e),i=r[0],e=r[1],i&&(n=l(i))),{f:i?i+"!"+e:e,n:e,pr:i,p:n}},g={require:function(e){return a(e)},exports:function(e){var t=m[e];return"undefined"!=typeof t?t:m[e]={}},module:function(e){return{id:e,uri:"",exports:m[e],config:f(e)}}},p=function(e,t,n,o){var s,c,f,p,d,v,x=[];if(o=o||e,"function"==typeof n){for(t=!t.length&&n.length?["require","exports","module"]:t,d=0;d<t.length;d+=1)if(p=h(t[d],o),c=p.f,"require"===c)x[d]=g.require(e);else if("exports"===c)x[d]=g.exports(e),v=!0;else if("module"===c)s=x[d]=g.module(e);else if(i(m,c)||i(y,c)||i(b,c))x[d]=l(c);else{if(!p.p)throw new Error(e+" missing "+c);p.p.load(p.n,a(o,!0),u(c),{}),x[d]=m[c]}f=n.apply(m[e],x),e&&(s&&s.exports!==r&&s.exports!==m[e]?m[e]=s.exports:f===r&&v||(m[e]=f))}else e&&(m[e]=n)},e=t=d=function(e,t,n,i,o){return"string"==typeof e?g[e]?g[e](t):l(h(e,t).f):(e.splice||(v=e,t.splice?(e=t,t=n,n=null):e=r),t=t||function(){},"function"==typeof n&&(n=i,i=o),i?p(r,e,t,n):setTimeout(function(){p(r,e,t,n)},4),d)},d.config=function(e){return v=e,v.deps&&d(v.deps,v.callback),d},e._defined=m,n=function(e,t,n){t.splice||(n=t,t=[]),i(m,e)||i(y,e)||(y[e]=[e,t,n])},n.amd={jQuery:!0}}(),n("almond",function(){}),function(e,t){function r(e){var t=e.length,n=lt.type(e);return lt.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}function i(e){var t=Nt[e]={};return lt.each(e.match(ft)||[],function(e,n){t[n]=!0}),t}function o(e,n,r,i){if(lt.acceptData(e)){var o,a,s=lt.expando,u="string"==typeof n,l=e.nodeType,c=l?lt.cache:e,f=l?e[s]:e[s]&&s;if(f&&c[f]&&(i||c[f].data)||!u||r!==t)return f||(l?e[s]=f=et.pop()||lt.guid++:f=s),c[f]||(c[f]={},l||(c[f].toJSON=lt.noop)),("object"==typeof n||"function"==typeof n)&&(i?c[f]=lt.extend(c[f],n):c[f].data=lt.extend(c[f].data,n)),o=c[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[lt.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[lt.camelCase(n)])):a=o,a}}function a(e,t,n){if(lt.acceptData(e)){var r,i,o,a=e.nodeType,s=a?lt.cache:e,l=a?e[lt.expando]:lt.expando;if(s[l]){if(t&&(o=n?s[l]:s[l].data)){lt.isArray(t)?t=t.concat(lt.map(t,lt.camelCase)):t in o?t=[t]:(t=lt.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?u:lt.isEmptyObject)(o))return}(n||(delete s[l].data,u(s[l])))&&(a?lt.cleanData([e],!0):lt.support.deleteExpando||s!=s.window?delete s[l]:s[l]=null)}}}function s(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(Et,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:kt.test(r)?lt.parseJSON(r):r}catch(o){}lt.data(e,n,r)}else r=t}return r}function u(e){var t;for(t in e)if(("data"!==t||!lt.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function l(){return!0}function c(){return!1}function f(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function p(e,t,n){if(t=t||0,lt.isFunction(t))return lt.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return lt.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=lt.grep(e,function(e){return 1===e.nodeType});if(Xt.test(t))return lt.filter(t,r,!n);t=lt.filter(t,r)}return lt.grep(e,function(e){return lt.inArray(e,t)>=0===n})}function d(e){var t=Ut.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function h(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function g(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function m(e){var t=an.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function y(e,t){for(var n,r=0;null!=(n=e[r]);r++)lt._data(n,"globalEval",!t||lt._data(t[r],"globalEval"))}function v(e,t){if(1===t.nodeType&&lt.hasData(e)){var n,r,i,o=lt._data(e),a=lt._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++)lt.event.add(t,n,s[n][r])}a.data&&(a.data=lt.extend({},a.data))}}function b(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!lt.support.noCloneEvent&&t[lt.expando]){i=lt._data(t);for(r in i.events)lt.removeEvent(t,r,i.handle);t.removeAttribute(lt.expando)}"script"===n&&t.text!==e.text?(g(t).text=e.text,m(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),lt.support.html5Clone&&e.innerHTML&&!lt.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&nn.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}function x(e,n){var r,i,o=0,a=typeof e.getElementsByTagName!==V?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==V?e.querySelectorAll(n||"*"):t;if(!a)for(a=[],r=e.childNodes||e;null!=(i=r[o]);o++)!n||lt.nodeName(i,n)?a.push(i):lt.merge(a,x(i,n));return n===t||n&&lt.nodeName(e,n)?lt.merge([e],a):a}function w(e){nn.test(e.type)&&(e.defaultChecked=e.checked)}function T(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=En.length;i--;)if(t=En[i]+n,t in e)return t;return r}function C(e,t){return e=t||e,"none"===lt.css(e,"display")||!lt.contains(e.ownerDocument,e)}function N(e,t){for(var n,r,i,o=[],a=0,s=e.length;s>a;a++)r=e[a],r.style&&(o[a]=lt._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&C(r)&&(o[a]=lt._data(r,"olddisplay",A(r.nodeName)))):o[a]||(i=C(r),(n&&"none"!==n||!i)&&lt._data(r,"olddisplay",i?n:lt.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}function k(e,t,n){var r=bn.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function E(e,t,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;4>o;o+=2)"margin"===n&&(a+=lt.css(e,n+kn[o],!0,i)),r?("content"===n&&(a-=lt.css(e,"padding"+kn[o],!0,i)),"margin"!==n&&(a-=lt.css(e,"border"+kn[o]+"Width",!0,i))):(a+=lt.css(e,"padding"+kn[o],!0,i),"padding"!==n&&(a+=lt.css(e,"border"+kn[o]+"Width",!0,i)));return a}function S(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=pn(e),a=lt.support.boxSizing&&"border-box"===lt.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=dn(e,t,o),(0>i||null==i)&&(i=e.style[t]),xn.test(i))return i;r=a&&(lt.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+E(e,t,n||(a?"border":"content"),r,o)+"px"}function A(e){var t=G,n=Tn[e];return n||(n=D(e,t),"none"!==n&&n||(fn=(fn||lt("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(fn[0].contentWindow||fn[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=D(e,t),fn.detach()),Tn[e]=n),n}function D(e,t){var n=lt(t.createElement(e)).appendTo(t.body),r=lt.css(n[0],"display");return n.remove(),r}function j(e,t,n,r){var i;if(lt.isArray(t))lt.each(t,function(t,i){n||An.test(e)?r(e,i):j(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==lt.type(t))r(e,t);else for(i in t)j(e+"["+i+"]",t[i],n,r)}function L(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(ft)||[];if(lt.isFunction(n))for(;r=o[i++];)"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function _(e,t,n,r){function i(s){var u;return o[s]=!0,lt.each(e[s]||[],function(e,s){var l=s(t,n,r);return"string"!=typeof l||a||o[l]?a?!(u=l):void 0:(t.dataTypes.unshift(l),i(l),!1)}),u}var o={},a=e===zn;return i(t.dataTypes[0])||!o["*"]&&i("*")}function H(e,n){var r,i,o=lt.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&lt.extend(!0,e,r),e}function O(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]);for(;"*"===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]):void 0}function q(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(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}}function $(){try{return new e.XMLHttpRequest}catch(t){}}function M(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function F(){return setTimeout(function(){er=t}),er=lt.now()}function B(e,t){lt.each(t,function(t,n){for(var r=(ar[t]||[]).concat(ar["*"]),i=0,o=r.length;o>i;i++)if(r[i].call(e,t,n))return})}function P(e,t,n){var r,i,o=0,a=or.length,s=lt.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;for(var t=er||F(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:lt.extend({},t),opts:lt.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:er||F(),duration:n.duration,tweens:[],createTween:function(t,n){var r=lt.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(I(c,l.opts.specialEasing);a>o;o++)if(r=or[o].call(l,e,c,l.opts))return r;return B(l,c),lt.isFunction(l.opts.start)&&l.opts.start.call(e,l),lt.fx.timer(lt.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 I(e,t){var n,r,i,o,a;for(i in e)if(r=lt.camelCase(i),o=t[r],n=e[i],lt.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=lt.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}function R(e,t,n){var r,i,o,a,s,u,l,c,f,p=this,d=e.style,h={},g=[],m=e.nodeType&&C(e);n.queue||(c=lt._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,f=c.empty.fire,c.empty.fire=function(){c.unqueued||f()}),c.unqueued++,p.always(function(){p.always(function(){c.unqueued--,lt.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"===lt.css(e,"display")&&"none"===lt.css(e,"float")&&(lt.support.inlineBlockNeedsLayout&&"inline"!==A(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",lt.support.shrinkWrapBlocks||p.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],nr.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=lt._data(e,"fxshow")||lt._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?lt(e).show():p.done(function(){lt(e).hide()}),p.done(function(){var t;lt._removeData(e,"fxshow");for(t in h)lt.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=p.createTween(r,m?s[r]:0),h[r]=s[r]||lt.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function W(e,t,n,r,i){return new W.prototype.init(e,t,n,r,i)}function X(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=kn[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function z(e){return lt.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var Y,U,V=typeof t,G=e.document,J=e.location,K=e.jQuery,Q=e.$,Z={},et=[],tt="1.9.1",nt=et.concat,rt=et.push,it=et.slice,ot=et.indexOf,at=Z.toString,st=Z.hasOwnProperty,ut=tt.trim,lt=function(e,t){return new lt.fn.init(e,t,U)},ct=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,ft=/\S+/g,pt=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,dt=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,ht=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,gt=/^[\],:{}\s]*$/,mt=/(?:^|:|,)(?:\s*\[)+/g,yt=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,vt=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,bt=/^-ms-/,xt=/-([\da-z])/gi,wt=function(e,t){return t.toUpperCase()},Tt=function(e){(G.addEventListener||"load"===e.type||"complete"===G.readyState)&&(Ct(),lt.ready())},Ct=function(){G.addEventListener?(G.removeEventListener("DOMContentLoaded",Tt,!1),e.removeEventListener("load",Tt,!1)):(G.detachEvent("onreadystatechange",Tt),e.detachEvent("onload",Tt))};lt.fn=lt.prototype={jquery:tt,constructor:lt,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:dt.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 lt?n[0]:n,lt.merge(this,lt.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:G,!0)),ht.test(i[1])&&lt.isPlainObject(n))for(i in n)lt.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=G.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=G,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):lt.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),lt.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return it.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=lt.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return lt.each(this,e,t)},ready:function(e){return lt.ready.promise().done(e),this},slice:function(){return this.pushStack(it.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(lt.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:rt,sort:[].sort,splice:[].splice},lt.fn.init.prototype=lt.fn,lt.extend=lt.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||lt.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&&(lt.isPlainObject(r)||(n=lt.isArray(r)))?(n?(n=!1,a=e&&lt.isArray(e)?e:[]):a=e&&lt.isPlainObject(e)?e:{},s[i]=lt.extend(c,a,r)):r!==t&&(s[i]=r));return s},lt.extend({noConflict:function(t){return e.$===lt&&(e.$=Q),t&&e.jQuery===lt&&(e.jQuery=K),lt},isReady:!1,readyWait:1,holdReady:function(e){e?lt.readyWait++:lt.ready(!0)},ready:function(e){if(e===!0?!--lt.readyWait:!lt.isReady){if(!G.body)return setTimeout(lt.ready);lt.isReady=!0,e!==!0&&--lt.readyWait>0||(Y.resolveWith(G,[lt]),lt.fn.trigger&&lt(G).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===lt.type(e)},isArray:Array.isArray||function(e){return"array"===lt.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?String(e):"object"==typeof e||"function"==typeof e?Z[at.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==lt.type(e)||e.nodeType||lt.isWindow(e))return!1;try{if(e.constructor&&!st.call(e,"constructor")&&!st.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||st.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||G;var r=ht.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=lt.buildFragment([e],t,i),i&&lt(i).remove(),lt.merge([],r.childNodes))},parseJSON:function(t){return e.JSON&&e.JSON.parse?e.JSON.parse(t):null===t?t:"string"==typeof t&&(t=lt.trim(t),t&&gt.test(t.replace(yt,"@").replace(vt,"]").replace(mt,"")))?new Function("return "+t)():(lt.error("Invalid JSON: "+t),void 0)},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||lt.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&lt.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(bt,"ms-").replace(xt,wt)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var i,o=0,a=e.length,s=r(e);if(n){if(s)for(;a>o&&(i=t.apply(e[o],n),i!==!1);o++);else for(o in e)if(i=t.apply(e[o],n),i===!1)break}else if(s)for(;a>o&&(i=t.call(e[o],o,e[o]),i!==!1);o++);else for(o in e)if(i=t.call(e[o],o,e[o]),i===!1)break;return e},trim:ut&&!ut.call(" ")?function(e){return null==e?"":ut.call(e)}:function(e){return null==e?"":(e+"").replace(pt,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(r(Object(e))?lt.merge(n,"string"==typeof e?[e]:e):rt.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(ot)return ot.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else for(;n[o]!==t;)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var i,o=0,a=e.length,s=r(e),u=[];if(s)for(;a>o;o++)i=t(e[o],o,n),null!=i&&(u[u.length]=i);else for(o in e)i=t(e[o],o,n),null!=i&&(u[u.length]=i);return nt.apply([],u)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),lt.isFunction(e)?(r=it.call(arguments,2),i=function(){return e.apply(n||this,r.concat(it.call(arguments)))},i.guid=e.guid=e.guid||lt.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===lt.type(r)){o=!0;for(u in r)lt.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,lt.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(lt(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()}}),lt.ready.promise=function(t){if(!Y)if(Y=lt.Deferred(),"complete"===G.readyState)setTimeout(lt.ready);else if(G.addEventListener)G.addEventListener("DOMContentLoaded",Tt,!1),e.addEventListener("load",Tt,!1);else{G.attachEvent("onreadystatechange",Tt),e.attachEvent("onload",Tt);var n=!1;try{n=null==e.frameElement&&G.documentElement}catch(r){}n&&n.doScroll&&!function i(){if(!lt.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}Ct(),lt.ready()}}()}return Y.promise(t)},lt.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){Z["[object "+t+"]"]=t.toLowerCase()}),U=lt(G);var Nt={};lt.Callbacks=function(e){e="string"==typeof e?Nt[e]||i(e):lt.extend({},e);var n,r,o,a,s,u,l=[],c=!e.once&&[],f=function(t){for(r=e.memory&&t,o=!0,s=u||0,u=0,a=l.length,n=!0;l&&a>s;s++)if(l[s].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(c?c.length&&f(c.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;!function i(t){lt.each(t,function(t,n){var r=lt.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})}(arguments),n?a=l.length:r&&(u=t,f(r))}return this},remove:function(){return l&&lt.each(arguments,function(e,t){for(var r;(r=lt.inArray(t,l,r))>-1;)l.splice(r,1),n&&(a>=r&&a--,s>=r&&s--)}),this},has:function(e){return e?lt.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],this},disable:function(){return l=c=r=t,this},disabled:function(){return!l},lock:function(){return c=t,r||p.disable(),this},locked:function(){return!c},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!l||o&&!c||(n?c.push(t):f(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!o}};return p},lt.extend({Deferred:function(e){var t=[["resolve","done",lt.Callbacks("once memory"),"resolved"],["reject","fail",lt.Callbacks("once memory"),"rejected"],["notify","progress",lt.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return lt.Deferred(function(n){lt.each(t,function(t,o){var a=o[0],s=lt.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&lt.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?lt.extend(e,r):r}},i={};return r.pipe=r.then,lt.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t,n,r,i=0,o=it.call(arguments),a=o.length,s=1!==a||e&&lt.isFunction(e.promise)?a:0,u=1===s?e:lt.Deferred(),l=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?it.call(arguments):i,r===t?u.notifyWith(n,r):--s||u.resolveWith(n,r)}};if(a>1)for(t=new Array(a),n=new Array(a),r=new Array(a);a>i;i++)o[i]&&lt.isFunction(o[i].promise)?o[i].promise().done(l(i,r,o)).fail(u.reject).progress(l(i,n,t)):--s;return s||u.resolveWith(r,o),u.promise()}}),lt.support=function(){var t,n,r,i,o,a,s,u,l,c,f=G.createElement("div");if(f.setAttribute("className","t"),f.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=f.getElementsByTagName("*"),r=f.getElementsByTagName("a")[0],!n||!r||!n.length)return{};o=G.createElement("select"),s=o.appendChild(G.createElement("option")),i=f.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==f.className,leadingWhitespace:3===f.firstChild.nodeType,tbody:!f.getElementsByTagName("tbody").length,htmlSerialize:!!f.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:!!i.value,optSelected:s.selected,enctype:!!G.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==G.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===G.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},i.checked=!0,t.noCloneChecked=i.cloneNode(!0).checked,o.disabled=!0,t.optDisabled=!s.disabled;try{delete f.test}catch(p){t.deleteExpando=!1}i=G.createElement("input"),i.setAttribute("value",""),t.input=""===i.getAttribute("value"),i.value="t",i.setAttribute("type","radio"),t.radioValue="t"===i.value,i.setAttribute("checked","t"),i.setAttribute("name","t"),a=G.createDocumentFragment(),a.appendChild(i),t.appendChecked=i.checked,t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,f.attachEvent&&(f.attachEvent("onclick",function(){t.noCloneEvent=!1}),f.cloneNode(!0).click());for(c in{submit:!0,change:!0,focusin:!0})f.setAttribute(u="on"+c,"t"),t[c+"Bubbles"]=u in e||f.attributes[u].expando===!1;return f.style.backgroundClip="content-box",f.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===f.style.backgroundClip,lt(function(){var n,r,i,o="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",a=G.getElementsByTagName("body")[0];a&&(n=G.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",a.appendChild(n).appendChild(f),f.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=f.getElementsByTagName("td"),i[0].style.cssText="padding:0;margin:0;border:0;display:none",l=0===i[0].offsetHeight,i[0].style.display="",i[1].style.display="none",t.reliableHiddenOffsets=l&&0===i[0].offsetHeight,f.innerHTML="",f.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===f.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==a.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(f,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(f,null)||{width:"4px"}).width,r=f.appendChild(G.createElement("div")),r.style.cssText=f.style.cssText=o,r.style.marginRight=r.style.width="0",f.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof f.style.zoom!==V&&(f.innerHTML="",f.style.cssText=o+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===f.offsetWidth,f.style.display="block",f.innerHTML="<div></div>",f.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==f.offsetWidth,t.inlineBlockNeedsLayout&&(a.style.zoom=1)),a.removeChild(n),n=f=i=r=null)}),n=o=a=s=r=i=null,t}();var kt=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,Et=/([A-Z])/g;lt.extend({cache:{},expando:"jQuery"+(tt+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?lt.cache[e[lt.expando]]:e[lt.expando],!!e&&!u(e)},data:function(e,t,n){return o(e,t,n)},removeData:function(e,t){return a(e,t)},_data:function(e,t,n){return o(e,t,n,!0)},_removeData:function(e,t){return a(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&lt.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),lt.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,u=null;if(e===t){if(this.length&&(u=lt.data(o),1===o.nodeType&&!lt._data(o,"parsedAttrs"))){for(r=o.attributes;a<r.length;a++)i=r[a].name,i.indexOf("data-")||(i=lt.camelCase(i.slice(5)),s(o,i,u[i]));lt._data(o,"parsedAttrs",!0)}return u}return"object"==typeof e?this.each(function(){lt.data(this,e)}):lt.access(this,function(n){return n===t?o?s(o,e,lt.data(o,e)):null:(this.each(function(){lt.data(this,e,n)}),void 0)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){lt.removeData(this,e)})}}),lt.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=lt._data(e,t),n&&(!r||lt.isArray(n)?r=lt._data(e,t,lt.makeArray(n)):r.push(n)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=lt.queue(e,t),r=n.length,i=n.shift(),o=lt._queueHooks(e,t),a=function(){lt.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 lt._data(e,n)||lt._data(e,n,{empty:lt.Callbacks("once memory").add(function(){lt._removeData(e,t+"queue"),lt._removeData(e,n)})})}}),lt.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),arguments.length<r?lt.queue(this[0],e):n===t?this:this.each(function(){var t=lt.queue(this,e,n);lt._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&lt.dequeue(this,e)})},dequeue:function(e){return this.each(function(){lt.dequeue(this,e)})},delay:function(e,t){return e=lt.fx?lt.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=lt.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};for("string"!=typeof e&&(n=e,e=t),e=e||"fx";s--;)r=lt._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var St,At,Dt=/[\t\r\n]/g,jt=/\r/g,Lt=/^(?:input|select|textarea|button|object)$/i,_t=/^(?:a|area)$/i,Ht=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,Ot=/^(?:checked|selected)$/i,qt=lt.support.getSetAttribute,$t=lt.support.input;lt.fn.extend({attr:function(e,t){return lt.access(this,lt.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){lt.removeAttr(this,e)})},prop:function(e,t){return lt.access(this,lt.prop,e,t,arguments.length>1)},removeProp:function(e){return e=lt.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(lt.isFunction(e))return this.each(function(t){lt(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(ft)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Dt," "):" ")){for(o=0;i=t[o++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");n.className=lt.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(lt.isFunction(e))return this.each(function(t){lt(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(ft)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Dt," "):"")){for(o=0;i=t[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");n.className=e?lt.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return lt.isFunction(e)?this.each(function(n){lt(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n)for(var i,o=0,a=lt(this),s=t,u=e.match(ft)||[];i=u[o++];)s=r?s:!a.hasClass(i),a[s?"addClass":"removeClass"](i);else(n===V||"boolean"===n)&&(this.className&&lt._data(this,"__className__",this.className),this.className=this.className||e===!1?"":lt._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(Dt," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=lt.isFunction(e),this.each(function(n){var o,a=lt(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":lt.isArray(o)&&(o=lt.map(o,function(e){return null==e?"":e+"" })),r=lt.valHooks[this.type]||lt.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=lt.valHooks[o.type]||lt.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(jt,""):null==n?"":n)}}}),lt.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){for(var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(lt.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&lt.nodeName(n.parentNode,"optgroup"))){if(t=lt(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=lt.makeArray(t);return lt(e).find("option").each(function(){this.selected=lt.inArray(lt(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===V?lt.prop(e,n,r):(o=1!==s||!lt.isXMLDoc(e),o&&(n=n.toLowerCase(),i=lt.attrHooks[n]||(Ht.test(n)?At:St)),r===t?i&&o&&"get"in i&&null!==(a=i.get(e,n))?a:(typeof e.getAttribute!==V&&(a=e.getAttribute(n)),null==a?t:a):null!==r?i&&o&&"set"in i&&(a=i.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(lt.removeAttr(e,n),void 0))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(ft);if(o&&1===e.nodeType)for(;n=o[i++];)r=lt.propFix[n]||n,Ht.test(n)?!qt&&Ot.test(n)?e[lt.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:lt.attr(e,n,""),e.removeAttribute(qt?n:r)},attrHooks:{type:{set:function(e,t){if(!lt.support.radioValue&&"radio"===t&&lt.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||!lt.isXMLDoc(e),a&&(n=lt.propFix[n]||n,o=lt.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):Lt.test(e.nodeName)||_t.test(e.nodeName)&&e.href?0:t}}}}),At={get:function(e,n){var r=lt.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?$t&&qt?null!=i:Ot.test(n)?e[lt.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?lt.removeAttr(e,n):$t&&qt||!Ot.test(n)?e.setAttribute(!qt&&lt.propFix[n]||n,n):e[lt.camelCase("default-"+n)]=e[n]=!0,n}},$t&&qt||(lt.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return lt.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,t,n){return lt.nodeName(e,"input")?(e.defaultValue=t,void 0):St&&St.set(e,t,n)}}),qt||(St=lt.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}},lt.attrHooks.contenteditable={get:St.get,set:function(e,t,n){St.set(e,""===t?!1:t,n)}},lt.each(["width","height"],function(e,t){lt.attrHooks[t]=lt.extend(lt.attrHooks[t],{set:function(e,n){return""===n?(e.setAttribute(t,"auto"),n):void 0}})})),lt.support.hrefNormalized||(lt.each(["href","src","width","height"],function(e,n){lt.attrHooks[n]=lt.extend(lt.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),lt.each(["href","src"],function(e,t){lt.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),lt.support.style||(lt.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),lt.support.optSelected||(lt.propHooks.selected=lt.extend(lt.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),lt.support.enctype||(lt.propFix.enctype="encoding"),lt.support.checkOn||lt.each(["radio","checkbox"],function(){lt.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),lt.each(["radio","checkbox"],function(){lt.valHooks[this]=lt.extend(lt.valHooks[this],{set:function(e,t){return lt.isArray(t)?e.checked=lt.inArray(lt(e).val(),t)>=0:void 0}})});var Mt=/^(?:input|select|textarea)$/i,Ft=/^key/,Bt=/^(?:mouse|contextmenu)|click/,Pt=/^(?:focusinfocus|focusoutblur)$/,It=/^([^.]*)(?:\.(.+)|)$/;lt.event={global:{},add:function(e,n,r,i,o){var a,s,u,l,c,f,p,d,h,g,m,y=lt._data(e);if(y){for(r.handler&&(l=r,r=l.handler,o=l.selector),r.guid||(r.guid=lt.guid++),(s=y.events)||(s=y.events={}),(f=y.handle)||(f=y.handle=function(e){return typeof lt===V||e&&lt.event.triggered===e.type?t:lt.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(ft)||[""],u=n.length;u--;)a=It.exec(n[u])||[],h=m=a[1],g=(a[2]||"").split(".").sort(),c=lt.event.special[h]||{},h=(o?c.delegateType:c.bindType)||h,c=lt.event.special[h]||{},p=lt.extend({type:h,origType:m,data:i,handler:r,guid:r.guid,selector:o,needsContext:o&&lt.expr.match.needsContext.test(o),namespace:g.join(".")},l),(d=s[h])||(d=s[h]=[],d.delegateCount=0,c.setup&&c.setup.call(e,i,g,f)!==!1||(e.addEventListener?e.addEventListener(h,f,!1):e.attachEvent&&e.attachEvent("on"+h,f))),c.add&&(c.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),o?d.splice(d.delegateCount++,0,p):d.push(p),lt.event.global[h]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,m=lt.hasData(e)&&lt._data(e);if(m&&(c=m.events)){for(t=(t||"").match(ft)||[""],l=t.length;l--;)if(s=It.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){for(f=lt.event.special[d]||{},d=(r?f.delegateType:f.bindType)||d,p=c[d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=p.length;o--;)a=p[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(p.splice(o,1),a.selector&&p.delegateCount--,f.remove&&f.remove.call(e,a));u&&!p.length&&(f.teardown&&f.teardown.call(e,h,m.handle)!==!1||lt.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)lt.event.remove(e,d+t[l],n,r,!0);lt.isEmptyObject(c)&&(delete m.handle,lt._removeData(e,"events"))}},trigger:function(n,r,i,o){var a,s,u,l,c,f,p,d=[i||G],h=st.call(n,"type")?n.type:n,g=st.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||G,3!==i.nodeType&&8!==i.nodeType&&!Pt.test(h+lt.event.triggered)&&(h.indexOf(".")>=0&&(g=h.split("."),h=g.shift(),g.sort()),s=h.indexOf(":")<0&&"on"+h,n=n[lt.expando]?n:new lt.Event(h,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=g.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+g.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:lt.makeArray(r,[n]),c=lt.event.special[h]||{},o||!c.trigger||c.trigger.apply(i,r)!==!1)){if(!o&&!c.noBubble&&!lt.isWindow(i)){for(l=c.delegateType||h,Pt.test(l+h)||(u=u.parentNode);u;u=u.parentNode)d.push(u),f=u;f===(i.ownerDocument||G)&&d.push(f.defaultView||f.parentWindow||e)}for(p=0;(u=d[p++])&&!n.isPropagationStopped();)n.type=p>1?l:c.bindType||h,a=(lt._data(u,"events")||{})[n.type]&&lt._data(u,"handle"),a&&a.apply(u,r),a=s&&u[s],a&&lt.acceptData(u)&&a.apply&&a.apply(u,r)===!1&&n.preventDefault();if(n.type=h,!(o||n.isDefaultPrevented()||c._default&&c._default.apply(i.ownerDocument,r)!==!1||"click"===h&&lt.nodeName(i,"a")||!lt.acceptData(i)||!s||!i[h]||lt.isWindow(i))){f=i[s],f&&(i[s]=null),lt.event.triggered=h;try{i[h]()}catch(m){}lt.event.triggered=t,f&&(i[s]=f)}return n.result}},dispatch:function(e){e=lt.event.fix(e);var n,r,i,o,a,s=[],u=it.call(arguments),l=(lt._data(this,"events")||{})[e.type]||[],c=lt.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){for(s=lt.event.handlers.call(this,e,l),n=0;(o=s[n++])&&!e.isPropagationStopped();)for(e.currentTarget=o.elem,a=0;(i=o.handlers[a++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((lt.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?lt(r,this).index(l)>=0:lt.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return u<n.length&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[lt.expando])return e;var t,n,r,i=e.type,o=e,a=this.fixHooks[i];for(a||(this.fixHooks[i]=a=Bt.test(i)?this.mouseHooks:Ft.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new lt.Event(o),t=r.length;t--;)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||G),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,a.filter?a.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,a=n.button,s=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||G,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&s&&(e.relatedTarget=s===e.target?n.toElement:s),e.which||a===t||(e.which=1&a?1:2&a?3:4&a?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return lt.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0}},focus:{trigger:function(){if(this!==G.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===G.activeElement&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=lt.extend(new lt.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?lt.event.trigger(i,null,t):lt.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},lt.removeEvent=G.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]===V&&(e[r]=null),e.detachEvent(r,n))},lt.Event=function(e,t){return this instanceof lt.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?l:c):this.type=e,t&&lt.extend(this,t),this.timeStamp=e&&e.timeStamp||lt.now(),this[lt.expando]=!0,void 0):new lt.Event(e,t)},lt.Event.prototype={isDefaultPrevented:c,isPropagationStopped:c,isImmediatePropagationStopped:c,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=l,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=l,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=l,this.stopPropagation()}},lt.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){lt.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!lt.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),lt.support.submitBubbles||(lt.event.special.submit={setup:function(){return lt.nodeName(this,"form")?!1:(lt.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=lt.nodeName(n,"input")||lt.nodeName(n,"button")?n.form:t;r&&!lt._data(r,"submitBubbles")&&(lt.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),lt._data(r,"submitBubbles",!0))}),void 0)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&lt.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return lt.nodeName(this,"form")?!1:(lt.event.remove(this,"._submit"),void 0)}}),lt.support.changeBubbles||(lt.event.special.change={setup:function(){return Mt.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(lt.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),lt.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),lt.event.simulate("change",this,e,!0)})),!1):(lt.event.add(this,"beforeactivate._change",function(e){var t=e.target;Mt.test(t.nodeName)&&!lt._data(t,"changeBubbles")&&(lt.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||lt.event.simulate("change",this.parentNode,e,!0)}),lt._data(t,"changeBubbles",!0))}),void 0)},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return lt.event.remove(this,"._change"),!Mt.test(this.nodeName)}}),lt.support.focusinBubbles||lt.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){lt.event.simulate(t,e.target,lt.event.fix(e),!0)};lt.event.special[t]={setup:function(){0===n++&&G.addEventListener(e,r,!0)},teardown:function(){0===--n&&G.removeEventListener(e,r,!0)}}}),lt.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=c;else if(!i)return this;return 1===o&&(s=i,i=function(e){return lt().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=lt.guid++)),this.each(function(){lt.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,lt(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=c),this.each(function(){lt.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(){lt.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?lt.event.trigger(e,t,n,!0):void 0}}),function(e,t){function n(e){return ht.test(e+"")}function r(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>N.cacheLength&&delete e[t.shift()],e[n]=r}}function i(e){return e[B]=!0,e}function o(e){var t=L.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function a(e,t,n,r){var i,o,a,s,u,l,c,d,h,g;if((t?t.ownerDocument||t:P)!==L&&j(t),t=t||L,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!H&&!r){if(i=gt.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&M(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return K.apply(n,Q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&I.getByClassName&&t.getElementsByClassName)return K.apply(n,Q.call(t.getElementsByClassName(a),0)),n}if(I.qsa&&!O.test(e)){if(c=!0,d=B,h=t,g=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){for(l=f(e),(c=t.getAttribute("id"))?d=c.replace(vt,"\\$&"):t.setAttribute("id",d),d="[id='"+d+"'] ",u=l.length;u--;)l[u]=d+p(l[u]);h=dt.test(e)&&t.parentNode||t,g=l.join(",")}if(g)try{return K.apply(n,Q.call(h.querySelectorAll(g),0)),n}catch(m){}finally{c||t.removeAttribute("id")}}}return x(e.replace(at,"$1"),t,n,r)}function s(e,t){var n=t&&e,r=n&&(~t.sourceIndex||V)-(~e.sourceIndex||V);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function u(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function l(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function c(e){return i(function(t){return t=+t,i(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function f(e,t){var n,r,i,o,s,u,l,c=z[e+" "];if(c)return t?0:c.slice(0);for(s=e,u=[],l=N.preFilter;s;){(!n||(r=st.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(i=[])),n=!1,(r=ut.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(at," ")}),s=s.slice(n.length));for(o in N.filter)!(r=pt[o].exec(s))||l[o]&&!(r=l[o](r))||(n=r.shift(),i.push({value:n,type:o,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?a.error(e):z(e,u).slice(0)}function p(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function d(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=W++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,u,l,c=R+" "+o;if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i)if(l=t[B]||(t[B]={}),(u=l[r])&&u[0]===c){if((s=u[1])===!0||s===C)return s===!0}else if(u=l[r]=[c],u[1]=e(t,n,a)||C,u[1]===!0)return!0}}function h(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function g(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function m(e,t,n,r,o,a){return r&&!r[B]&&(r=m(r)),o&&!o[B]&&(o=m(o,a)),i(function(i,a,s,u){var l,c,f,p=[],d=[],h=a.length,m=i||b(t||"*",s.nodeType?[s]:s,[]),y=!e||!i&&t?m:g(m,p,e,s,u),v=n?o||(i?e:h||r)?[]:a:y;if(n&&n(y,v,s,u),r)for(l=g(v,d),r(l,[],s,u),c=l.length;c--;)(f=l[c])&&(v[d[c]]=!(y[d[c]]=f));if(i){if(o||e){if(o){for(l=[],c=v.length;c--;)(f=v[c])&&l.push(y[c]=f);o(null,v=[],l,u)}for(c=v.length;c--;)(f=v[c])&&(l=o?Z.call(i,f):p[c])>-1&&(i[l]=!(a[l]=f))}}else v=g(v===a?v.splice(h,v.length):v),o?o(null,a,v,u):K.apply(a,v)})}function y(e){for(var t,n,r,i=e.length,o=N.relative[e[0].type],a=o||N.relative[" "],s=o?1:0,u=d(function(e){return e===t},a,!0),l=d(function(e){return Z.call(t,e)>-1},a,!0),c=[function(e,n,r){return!o&&(r||n!==D)||((t=n).nodeType?u(e,n,r):l(e,n,r))}];i>s;s++)if(n=N.relative[e[s].type])c=[d(h(c),n)];else{if(n=N.filter[e[s].type].apply(null,e[s].matches),n[B]){for(r=++s;i>r&&!N.relative[e[r].type];r++);return m(s>1&&h(c),s>1&&p(e.slice(0,s-1)).replace(at,"$1"),n,r>s&&y(e.slice(s,r)),i>r&&y(e=e.slice(r)),i>r&&p(e))}c.push(n)}return h(c)}function v(e,t){var n=0,r=t.length>0,o=e.length>0,s=function(i,s,u,l,c){var f,p,d,h=[],m=0,y="0",v=i&&[],b=null!=c,x=D,w=i||o&&N.find.TAG("*",c&&s.parentNode||s),T=R+=null==x?1:Math.random()||.1;for(b&&(D=s!==L&&s,C=n);null!=(f=w[y]);y++){if(o&&f){for(p=0;d=e[p++];)if(d(f,s,u)){l.push(f);break}b&&(R=T,C=++n)}r&&((f=!d&&f)&&m--,i&&v.push(f))}if(m+=y,r&&y!==m){for(p=0;d=t[p++];)d(v,h,s,u);if(i){if(m>0)for(;y--;)v[y]||h[y]||(h[y]=J.call(l));h=g(h)}K.apply(l,h),b&&!i&&h.length>0&&m+t.length>1&&a.uniqueSort(l)}return b&&(R=T,D=x),v};return r?i(s):s}function b(e,t,n){for(var r=0,i=t.length;i>r;r++)a(e,t[r],n);return n}function x(e,t,n,r){var i,o,a,s,u,l=f(e);if(!r&&1===l.length){if(o=l[0]=l[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&9===t.nodeType&&!H&&N.relative[o[1].type]){if(t=N.find.ID(a.matches[0].replace(xt,wt),t)[0],!t)return n;e=e.slice(o.shift().value.length)}for(i=pt.needsContext.test(e)?0:o.length;i--&&(a=o[i],!N.relative[s=a.type]);)if((u=N.find[s])&&(r=u(a.matches[0].replace(xt,wt),dt.test(o[0].type)&&t.parentNode||t))){if(o.splice(i,1),e=r.length&&p(o),!e)return K.apply(n,Q.call(r,0)),n;break}}return S(e,l)(r,t,H,n,dt.test(e)),n}function w(){}var T,C,N,k,E,S,A,D,j,L,_,H,O,q,$,M,F,B="sizzle"+-new Date,P=e.document,I={},R=0,W=0,X=r(),z=r(),Y=r(),U=typeof t,V=1<<31,G=[],J=G.pop,K=G.push,Q=G.slice,Z=G.indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},et="[\\x20\\t\\r\\n\\f]",tt="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",nt=tt.replace("w","w#"),rt="([*^$|!~]?=)",it="\\["+et+"*("+tt+")"+et+"*(?:"+rt+et+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+nt+")|)|)"+et+"*\\]",ot=":("+tt+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+it.replace(3,8)+")*)|.*)\\)|)",at=new RegExp("^"+et+"+|((?:^|[^\\\\])(?:\\\\.)*)"+et+"+$","g"),st=new RegExp("^"+et+"*,"+et+"*"),ut=new RegExp("^"+et+"*([\\x20\\t\\r\\n\\f>+~])"+et+"*"),ct=new RegExp(ot),ft=new RegExp("^"+nt+"$"),pt={ID:new RegExp("^#("+tt+")"),CLASS:new RegExp("^\\.("+tt+")"),NAME:new RegExp("^\\[name=['\"]?("+tt+")['\"]?\\]"),TAG:new RegExp("^("+tt.replace("w","w*")+")"),ATTR:new RegExp("^"+it),PSEUDO:new RegExp("^"+ot),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+et+"*(even|odd|(([+-]|)(\\d*)n|)"+et+"*(?:([+-]|)"+et+"*(\\d+)|))"+et+"*\\)|)","i"),needsContext:new RegExp("^"+et+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+et+"*((?:-\\d)?\\d*)"+et+"*\\)|)(?=[^-]|$)","i")},dt=/[\x20\t\r\n\f]*[+~]/,ht=/^[^{]+\{\s*\[native code/,gt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,mt=/^(?:input|select|textarea|button)$/i,yt=/^h\d$/i,vt=/'|\\/g,bt=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,xt=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,wt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320)};try{Q.call(P.documentElement.childNodes,0)[0].nodeType}catch(Tt){Q=function(e){for(var t,n=[];t=this[e++];)n.push(t);return n}}E=a.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},j=a.setDocument=function(e){var r=e?e.ownerDocument||e:P;return r!==L&&9===r.nodeType&&r.documentElement?(L=r,_=r.documentElement,H=E(r),I.tagNameNoComments=o(function(e){return e.appendChild(r.createComment("")),!e.getElementsByTagName("*").length}),I.attributes=o(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),I.getByClassName=o(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),I.getByName=o(function(e){e.id=B+0,e.innerHTML="<a name='"+B+"'></a><div name='"+B+"'></div>",_.insertBefore(e,_.firstChild);var t=r.getElementsByName&&r.getElementsByName(B).length===2+r.getElementsByName(B+0).length;return I.getIdNotName=!r.getElementById(B),_.removeChild(e),t}),N.attrHandle=o(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==U&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},I.getIdNotName?(N.find.ID=function(e,t){if(typeof t.getElementById!==U&&!H){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},N.filter.ID=function(e){var t=e.replace(xt,wt);return function(e){return e.getAttribute("id")===t}}):(N.find.ID=function(e,n){if(typeof n.getElementById!==U&&!H){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==U&&r.getAttributeNode("id").value===e?[r]:t:[]}},N.filter.ID=function(e){var t=e.replace(xt,wt);return function(e){var n=typeof e.getAttributeNode!==U&&e.getAttributeNode("id");return n&&n.value===t}}),N.find.TAG=I.tagNameNoComments?function(e,t){return typeof t.getElementsByTagName!==U?t.getElementsByTagName(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o},N.find.NAME=I.getByName&&function(e,t){return typeof t.getElementsByName!==U?t.getElementsByName(name):void 0},N.find.CLASS=I.getByClassName&&function(e,t){return typeof t.getElementsByClassName===U||H?void 0:t.getElementsByClassName(e)},q=[],O=[":focus"],(I.qsa=n(r.querySelectorAll))&&(o(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||O.push("\\["+et+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||O.push(":checked")}),o(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&O.push("[*^$]="+et+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||O.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),O.push(",.*:")})),(I.matchesSelector=n($=_.matchesSelector||_.mozMatchesSelector||_.webkitMatchesSelector||_.oMatchesSelector||_.msMatchesSelector))&&o(function(e){I.disconnectedMatch=$.call(e,"div"),$.call(e,"[s!='']:x"),q.push("!=",ot)}),O=new RegExp(O.join("|")),q=new RegExp(q.join("|")),M=n(_.contains)||_.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},F=_.compareDocumentPosition?function(e,t){var n;return e===t?(A=!0,0):(n=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&n||e.parentNode&&11===e.parentNode.nodeType?e===r||M(P,e)?-1:t===r||M(P,t)?1:0:4&n?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var n,i=0,o=e.parentNode,a=t.parentNode,u=[e],l=[t];if(e===t)return A=!0,0;if(!o||!a)return e===r?-1:t===r?1:o?-1:a?1:0;if(o===a)return s(e,t);for(n=e;n=n.parentNode;)u.unshift(n);for(n=t;n=n.parentNode;)l.unshift(n);for(;u[i]===l[i];)i++;return i?s(u[i],l[i]):u[i]===P?-1:l[i]===P?1:0},A=!1,[0,0].sort(F),I.detectDuplicates=A,L):L},a.matches=function(e,t){return a(e,null,null,t)},a.matchesSelector=function(e,t){if((e.ownerDocument||e)!==L&&j(e),t=t.replace(bt,"='$1']"),!(!I.matchesSelector||H||q&&q.test(t)||O.test(t)))try{var n=$.call(e,t);if(n||I.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return a(t,L,null,[e]).length>0},a.contains=function(e,t){return(e.ownerDocument||e)!==L&&j(e),M(e,t)},a.attr=function(e,t){var n;return(e.ownerDocument||e)!==L&&j(e),H||(t=t.toLowerCase()),(n=N.attrHandle[t])?n(e):H||I.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},a.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a.uniqueSort=function(e){var t,n=[],r=1,i=0;if(A=!I.detectDuplicates,e.sort(F),A){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));for(;i--;)e.splice(n[i],1)}return e},k=a.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=k(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=k(t);return n},N=a.selectors={cacheLength:50,createPseudo:i,match:pt,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(xt,wt),e[3]=(e[4]||e[5]||"").replace(xt,wt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||a.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&a.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return pt.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&ct.test(n)&&(t=f(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(xt,wt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=X[e+" "];return t||(t=new RegExp("(^|"+et+")"+e+"("+et+"|$)"))&&X(e,function(e){return t.test(e.className||typeof e.getAttribute!==U&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=a.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.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,f,p,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){for(;g;){for(f=t;f=f[g];)if(s?f.nodeName.toLowerCase()===y:1===f.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){for(c=m[B]||(m[B]={}),l=c[e]||[],d=l[0]===R&&l[1],p=l[0]===R&&l[2],f=d&&m.childNodes[d];f=++d&&f&&f[g]||(p=d=0)||h.pop();)if(1===f.nodeType&&++p&&f===t){c[e]=[R,d,p];break}}else if(v&&(l=(t[B]||(t[B]={}))[e])&&l[0]===R)p=l[1];else for(;(f=++d&&f&&f[g]||(p=d=0)||h.pop())&&((s?f.nodeName.toLowerCase()!==y:1!==f.nodeType)||!++p||(v&&((f[B]||(f[B]={}))[e]=[R,p]),f!==t)););return p-=i,p===r||p%r===0&&p/r>=0}}},PSEUDO:function(e,t){var n,r=N.pseudos[e]||N.setFilters[e.toLowerCase()]||a.error("unsupported pseudo: "+e);return r[B]?r(t):r.length>1?(n=[e,e,"",t],N.setFilters.hasOwnProperty(e.toLowerCase())?i(function(e,n){for(var i,o=r(e,t),a=o.length;a--;)i=Z.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:i(function(e){var t=[],n=[],r=S(e.replace(at,"$1"));return r[B]?i(function(e,t,n,i){for(var o,a=r(e,null,i,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:i(function(e){return function(t){return a(e,t).length>0}}),contains:i(function(e){return function(t){return(t.textContent||t.innerText||k(t)).indexOf(e)>-1}}),lang:i(function(e){return ft.test(e||"")||a.error("unsupported lang: "+e),e=e.replace(xt,wt).toLowerCase(),function(t){var n;do if(n=H?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===_},focus:function(e){return e===L.activeElement&&(!L.hasFocus||L.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!N.pseudos.empty(e)},header:function(e){return yt.test(e.nodeName)},input:function(e){return mt.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:c(function(){return[0]}),last:c(function(e,t){return[t-1] }),eq:c(function(e,t,n){return[0>n?n+t:n]}),even:c(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:c(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:c(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:c(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}};for(T in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})N.pseudos[T]=u(T);for(T in{submit:!0,reset:!0})N.pseudos[T]=l(T);S=a.compile=function(e,t){var n,r=[],i=[],o=Y[e+" "];if(!o){for(t||(t=f(e)),n=t.length;n--;)o=y(t[n]),o[B]?r.push(o):i.push(o);o=Y(e,v(i,r))}return o},N.pseudos.nth=N.pseudos.eq,N.filters=w.prototype=N.pseudos,N.setFilters=new w,j(),a.attr=lt.attr,lt.find=a,lt.expr=a.selectors,lt.expr[":"]=lt.expr.pseudos,lt.unique=a.uniqueSort,lt.text=a.getText,lt.isXMLDoc=a.isXML,lt.contains=a.contains}(e);var Rt=/Until$/,Wt=/^(?:parents|prev(?:Until|All))/,Xt=/^.[^:#\[\.,]*$/,zt=lt.expr.match.needsContext,Yt={children:!0,contents:!0,next:!0,prev:!0};lt.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(lt(e).filter(function(){for(t=0;i>t;t++)if(lt.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)lt.find(e,this[t],n);return n=this.pushStack(i>1?lt.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=lt(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(lt.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(p(this,e,!1))},filter:function(e){return this.pushStack(p(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?zt.test(e)?lt(e,this.context).index(this[0])>=0:lt.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=zt.test(e)||"string"!=typeof e?lt(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n.ownerDocument&&n!==t&&11!==n.nodeType;){if(a?a.index(n)>-1:lt.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}return this.pushStack(o.length>1?lt.unique(o):o)},index:function(e){return e?"string"==typeof e?lt.inArray(this[0],lt(e)):lt.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?lt(e,t):lt.makeArray(e&&e.nodeType?[e]:e),r=lt.merge(this.get(),n);return this.pushStack(lt.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),lt.fn.andSelf=lt.fn.addBack,lt.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return lt.dir(e,"parentNode")},parentsUntil:function(e,t,n){return lt.dir(e,"parentNode",n)},next:function(e){return f(e,"nextSibling")},prev:function(e){return f(e,"previousSibling")},nextAll:function(e){return lt.dir(e,"nextSibling")},prevAll:function(e){return lt.dir(e,"previousSibling")},nextUntil:function(e,t,n){return lt.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return lt.dir(e,"previousSibling",n)},siblings:function(e){return lt.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return lt.sibling(e.firstChild)},contents:function(e){return lt.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:lt.merge([],e.childNodes)}},function(e,t){lt.fn[e]=function(n,r){var i=lt.map(this,t,n);return Rt.test(e)||(r=n),r&&"string"==typeof r&&(i=lt.filter(r,i)),i=this.length>1&&!Yt[e]?lt.unique(i):i,this.length>1&&Wt.test(e)&&(i=i.reverse()),this.pushStack(i)}}),lt.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?lt.find.matchesSelector(t[0],e)?[t[0]]:[]:lt.find.matches(e,t)},dir:function(e,n,r){for(var i=[],o=e[n];o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!lt(o).is(r));)1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});var Ut="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Vt=/ jQuery\d+="(?:null|\d+)"/g,Gt=new RegExp("<(?:"+Ut+")[\\s/>]","i"),Jt=/^\s+/,Kt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Qt=/<([\w:]+)/,Zt=/<tbody/i,en=/<|&#?\w+;/,tn=/<(?:script|style|link)/i,nn=/^(?:checkbox|radio)$/i,rn=/checked\s*(?:[^=]|=\s*.checked.)/i,on=/^$|\/(?:java|ecma)script/i,an=/^true\/(.*)/,sn=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,un={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:lt.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},ln=d(G),cn=ln.appendChild(G.createElement("div"));un.optgroup=un.option,un.tbody=un.tfoot=un.colgroup=un.caption=un.thead,un.th=un.td,lt.fn.extend({text:function(e){return lt.access(this,function(e){return e===t?lt.text(this):this.empty().append((this[0]&&this[0].ownerDocument||G).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(lt.isFunction(e))return this.each(function(t){lt(this).wrapAll(e.call(this,t))});if(this[0]){var t=lt(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return lt.isFunction(e)?this.each(function(t){lt(this).wrapInner(e.call(this,t))}):this.each(function(){var t=lt(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=lt.isFunction(e);return this.each(function(n){lt(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){lt.nodeName(this,"body")||lt(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var n,r=0;null!=(n=this[r]);r++)(!e||lt.filter(e,[n]).length>0)&&(t||1!==n.nodeType||lt.cleanData(x(n)),n.parentNode&&(t&&lt.contains(n.ownerDocument,n)&&y(x(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&lt.cleanData(x(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&lt.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 lt.clone(this,e,t)})},html:function(e){return lt.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(Vt,""):t;if(!("string"!=typeof e||tn.test(e)||!lt.support.htmlSerialize&&Gt.test(e)||!lt.support.leadingWhitespace&&Jt.test(e)||un[(Qt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Kt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(lt.cleanData(x(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=lt.isFunction(e);return t||"string"==typeof e||(e=lt(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(lt(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=nt.apply([],e);var i,o,a,s,u,l,c=0,f=this.length,p=this,d=f-1,y=e[0],v=lt.isFunction(y);if(v||!(1>=f||"string"!=typeof y||lt.support.checkClone)&&rn.test(y))return this.each(function(i){var o=p.eq(i);v&&(e[0]=y.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(f&&(l=lt.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&lt.nodeName(i,"tr"),s=lt.map(x(l,"script"),g),a=s.length;f>c;c++)o=l,c!==d&&(o=lt.clone(o,!0,!0),a&&lt.merge(s,x(o,"script"))),r.call(n&&lt.nodeName(this[c],"table")?h(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,lt.map(s,m),c=0;a>c;c++)o=s[c],on.test(o.type||"")&&!lt._data(o,"globalEval")&&lt.contains(u,o)&&(o.src?lt.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):lt.globalEval((o.text||o.textContent||o.innerHTML||"").replace(sn,"")));l=i=null}return this}}),lt.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){lt.fn[e]=function(e){for(var n,r=0,i=[],o=lt(e),a=o.length-1;a>=r;r++)n=r===a?this:this.clone(!0),lt(o[r])[t](n),rt.apply(i,n.get());return this.pushStack(i)}}),lt.extend({clone:function(e,t,n){var r,i,o,a,s,u=lt.contains(e.ownerDocument,e);if(lt.support.html5Clone||lt.isXMLDoc(e)||!Gt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(cn.innerHTML=e.outerHTML,cn.removeChild(o=cn.firstChild)),!(lt.support.noCloneEvent&&lt.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||lt.isXMLDoc(e)))for(r=x(o),s=x(e),a=0;null!=(i=s[a]);++a)r[a]&&b(i,r[a]);if(t)if(n)for(s=s||x(e),r=r||x(o),a=0;null!=(i=s[a]);a++)v(i,r[a]);else v(e,o);return r=x(o,"script"),r.length>0&&y(r,!u&&x(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){for(var i,o,a,s,u,l,c,f=e.length,p=d(t),h=[],g=0;f>g;g++)if(o=e[g],o||0===o)if("object"===lt.type(o))lt.merge(h,o.nodeType?[o]:o);else if(en.test(o)){for(s=s||p.appendChild(t.createElement("div")),u=(Qt.exec(o)||["",""])[1].toLowerCase(),c=un[u]||un._default,s.innerHTML=c[1]+o.replace(Kt,"<$1></$2>")+c[2],i=c[0];i--;)s=s.lastChild;if(!lt.support.leadingWhitespace&&Jt.test(o)&&h.push(t.createTextNode(Jt.exec(o)[0])),!lt.support.tbody)for(o="table"!==u||Zt.test(o)?"<table>"!==c[1]||Zt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;i--;)lt.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l);for(lt.merge(h,s.childNodes),s.textContent="";s.firstChild;)s.removeChild(s.firstChild);s=p.lastChild}else h.push(t.createTextNode(o));for(s&&p.removeChild(s),lt.support.appendChecked||lt.grep(x(h,"input"),w),g=0;o=h[g++];)if((!r||-1===lt.inArray(o,r))&&(a=lt.contains(o.ownerDocument,o),s=x(p.appendChild(o),"script"),a&&y(s),n))for(i=0;o=s[i++];)on.test(o.type||"")&&n.push(o);return s=null,p},cleanData:function(e,t){for(var n,r,i,o,a=0,s=lt.expando,u=lt.cache,l=lt.support.deleteExpando,c=lt.event.special;null!=(n=e[a]);a++)if((t||lt.acceptData(n))&&(i=n[s],o=i&&u[i])){if(o.events)for(r in o.events)c[r]?lt.event.remove(n,r):lt.removeEvent(n,r,o.handle);u[i]&&(delete u[i],l?delete n[s]:typeof n.removeAttribute!==V?n.removeAttribute(s):n[s]=null,et.push(i))}}});var fn,pn,dn,hn=/alpha\([^)]*\)/i,gn=/opacity\s*=\s*([^)]*)/,mn=/^(top|right|bottom|left)$/,yn=/^(none|table(?!-c[ea]).+)/,vn=/^margin/,bn=new RegExp("^("+ct+")(.*)$","i"),xn=new RegExp("^("+ct+")(?!px)[a-z%]+$","i"),wn=new RegExp("^([+-])=("+ct+")","i"),Tn={BODY:"block"},Cn={position:"absolute",visibility:"hidden",display:"block"},Nn={letterSpacing:0,fontWeight:400},kn=["Top","Right","Bottom","Left"],En=["Webkit","O","Moz","ms"];lt.fn.extend({css:function(e,n){return lt.access(this,function(e,n,r){var i,o,a={},s=0;if(lt.isArray(n)){for(o=pn(e),i=n.length;i>s;s++)a[n[s]]=lt.css(e,n[s],!1,o);return a}return r!==t?lt.style(e,n,r):lt.css(e,n)},e,n,arguments.length>1)},show:function(){return N(this,!0)},hide:function(){return N(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:C(this))?lt(this).show():lt(this).hide()})}}),lt.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=dn(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":lt.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=lt.camelCase(n),l=e.style;if(n=lt.cssProps[u]||(lt.cssProps[u]=T(l,u)),s=lt.cssHooks[n]||lt.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=wn.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(lt.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||lt.cssNumber[u]||(r+="px"),lt.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=lt.camelCase(n);return n=lt.cssProps[u]||(lt.cssProps[u]=T(e.style,u)),s=lt.cssHooks[n]||lt.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=dn(e,n,i)),"normal"===a&&n in Nn&&(a=Nn[n]),""===r||r?(o=parseFloat(a),r===!0||lt.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?(pn=function(t){return e.getComputedStyle(t,null)},dn=function(e,n,r){var i,o,a,s=r||pn(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||lt.contains(e.ownerDocument,e)||(u=lt.style(e,n)),xn.test(u)&&vn.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}):G.documentElement.currentStyle&&(pn=function(e){return e.currentStyle},dn=function(e,n,r){var i,o,a,s=r||pn(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),xn.test(u)&&!mn.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}),lt.each(["height","width"],function(e,t){lt.cssHooks[t]={get:function(e,n,r){return n?0===e.offsetWidth&&yn.test(lt.css(e,"display"))?lt.swap(e,Cn,function(){return S(e,t,r)}):S(e,t,r):void 0},set:function(e,n,r){var i=r&&pn(e);return k(e,n,r?E(e,t,r,lt.support.boxSizing&&"border-box"===lt.css(e,"boxSizing",!1,i),i):0)}}}),lt.support.opacity||(lt.cssHooks.opacity={get:function(e,t){return gn.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=lt.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===lt.trim(o.replace(hn,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=hn.test(o)?o.replace(hn,i):o+" "+i)}}),lt(function(){lt.support.reliableMarginRight||(lt.cssHooks.marginRight={get:function(e,t){return t?lt.swap(e,{display:"inline-block"},dn,[e,"marginRight"]):void 0}}),!lt.support.pixelPosition&&lt.fn.position&&lt.each(["top","left"],function(e,t){lt.cssHooks[t]={get:function(e,n){return n?(n=dn(e,t),xn.test(n)?lt(e).position()[t]+"px":n):void 0}}})}),lt.expr&&lt.expr.filters&&(lt.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!lt.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||lt.css(e,"display"))},lt.expr.filters.visible=function(e){return!lt.expr.filters.hidden(e)}),lt.each({margin:"",padding:"",border:"Width"},function(e,t){lt.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+kn[r]+t]=o[r]||o[r-2]||o[0];return i}},vn.test(e)||(lt.cssHooks[e+t].set=k)});var Sn=/%20/g,An=/\[\]$/,Dn=/\r?\n/g,jn=/^(?:submit|button|image|reset|file)$/i,Ln=/^(?:input|select|textarea|keygen)/i;lt.fn.extend({serialize:function(){return lt.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=lt.prop(this,"elements");return e?lt.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!lt(this).is(":disabled")&&Ln.test(this.nodeName)&&!jn.test(e)&&(this.checked||!nn.test(e))}).map(function(e,t){var n=lt(this).val();return null==n?null:lt.isArray(n)?lt.map(n,function(e){return{name:t.name,value:e.replace(Dn,"\r\n")}}):{name:t.name,value:n.replace(Dn,"\r\n")}}).get()}}),lt.param=function(e,n){var r,i=[],o=function(e,t){t=lt.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=lt.ajaxSettings&&lt.ajaxSettings.traditional),lt.isArray(e)||e.jquery&&!lt.isPlainObject(e))lt.each(e,function(){o(this.name,this.value)});else for(r in e)j(r,e[r],n,o);return i.join("&").replace(Sn,"+")},lt.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){lt.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),lt.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var _n,Hn,On=lt.now(),qn=/\?/,$n=/#.*$/,Mn=/([?&])_=[^&]*/,Fn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Bn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Pn=/^(?:GET|HEAD)$/,In=/^\/\//,Rn=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Wn=lt.fn.load,Xn={},zn={},Yn="*/".concat("*");try{Hn=J.href}catch(Un){Hn=G.createElement("a"),Hn.href="",Hn=Hn.href}_n=Rn.exec(Hn.toLowerCase())||[],lt.fn.load=function(e,n,r){if("string"!=typeof e&&Wn)return Wn.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)),lt.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&lt.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?lt("<div>").append(lt.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},lt.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){lt.fn[t]=function(e){return this.on(t,e)}}),lt.each(["get","post"],function(e,n){lt[n]=function(e,r,i,o){return lt.isFunction(r)&&(o=o||i,i=r,r=t),lt.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),lt.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Hn,type:"GET",isLocal:Bn.test(_n[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Yn,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":lt.parseJSON,"text xml":lt.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?H(H(e,lt.ajaxSettings),t):H(lt.ajaxSettings,e)},ajaxPrefilter:L(Xn),ajaxTransport:L(zn),ajax:function(e,n){function r(e,n,r,i){var o,f,v,b,w,C=n;2!==x&&(x=2,u&&clearTimeout(u),c=t,s=i||"",T.readyState=e>0?4:0,r&&(b=O(p,T,r)),e>=200&&300>e||304===e?(p.ifModified&&(w=T.getResponseHeader("Last-Modified"),w&&(lt.lastModified[a]=w),w=T.getResponseHeader("etag"),w&&(lt.etag[a]=w)),204===e?(o=!0,C="nocontent"):304===e?(o=!0,C="notmodified"):(o=q(p,b),C=o.state,f=o.data,v=o.error,o=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),T.status=e,T.statusText=(n||C)+"",o?g.resolveWith(d,[f,C,T]):g.rejectWith(d,[T,C,v]),T.statusCode(y),y=t,l&&h.trigger(o?"ajaxSuccess":"ajaxError",[T,p,o?f:v]),m.fireWith(d,[T,C]),l&&(h.trigger("ajaxComplete",[T,p]),--lt.active||lt.event.trigger("ajaxStop")))}"object"==typeof e&&(n=e,e=t),n=n||{};var i,o,a,s,u,l,c,f,p=lt.ajaxSetup({},n),d=p.context||p,h=p.context&&(d.nodeType||d.jquery)?lt(d):lt.event,g=lt.Deferred(),m=lt.Callbacks("once memory"),y=p.statusCode||{},v={},b={},x=0,w="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!f)for(f={};t=Fn.exec(s);)f[t[1].toLowerCase()]=t[2];t=f[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?s:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=b[n]=b[n]||e,v[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)y[t]=[y[t],e[t]];else T.always(e[T.status]);return this},abort:function(e){var t=e||w;return c&&c.abort(t),r(0,t),this}};if(g.promise(T).complete=m.add,T.success=T.done,T.error=T.fail,p.url=((e||p.url||Hn)+"").replace($n,"").replace(In,_n[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=lt.trim(p.dataType||"*").toLowerCase().match(ft)||[""],null==p.crossDomain&&(i=Rn.exec(p.url.toLowerCase()),p.crossDomain=!(!i||i[1]===_n[1]&&i[2]===_n[2]&&(i[3]||("http:"===i[1]?80:443))==(_n[3]||("http:"===_n[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=lt.param(p.data,p.traditional)),_(Xn,p,n,T),2===x)return T;l=p.global,l&&0===lt.active++&&lt.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Pn.test(p.type),a=p.url,p.hasContent||(p.data&&(a=p.url+=(qn.test(a)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=Mn.test(a)?a.replace(Mn,"$1_="+On++):a+(qn.test(a)?"&":"?")+"_="+On++)),p.ifModified&&(lt.lastModified[a]&&T.setRequestHeader("If-Modified-Since",lt.lastModified[a]),lt.etag[a]&&T.setRequestHeader("If-None-Match",lt.etag[a])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&T.setRequestHeader("Content-Type",p.contentType),T.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Yn+"; q=0.01":""):p.accepts["*"]);for(o in p.headers)T.setRequestHeader(o,p.headers[o]);if(p.beforeSend&&(p.beforeSend.call(d,T,p)===!1||2===x))return T.abort();w="abort";for(o in{success:1,error:1,complete:1})T[o](p[o]);if(c=_(zn,p,n,T)){T.readyState=1,l&&h.trigger("ajaxSend",[T,p]),p.async&&p.timeout>0&&(u=setTimeout(function(){T.abort("timeout")},p.timeout));try{x=1,c.send(v,r)}catch(C){if(!(2>x))throw C;r(-1,C)}}else r(-1,"No Transport");return T},getScript:function(e,n){return lt.get(e,t,n,"script")},getJSON:function(e,t,n){return lt.get(e,t,n,"json")}}),lt.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return lt.globalEval(e),e}}}),lt.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),lt.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=G.head||lt("head")[0]||G.documentElement;return{send:function(t,i){n=G.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 Vn=[],Gn=/(=)\?(?=&|$)|\?\?/;lt.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Vn.pop()||lt.expando+"_"+On++;return this[e]=!0,e}}),lt.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Gn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Gn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=lt.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Gn,"$1"+o):n.jsonp!==!1&&(n.url+=(qn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||lt.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,Vn.push(o)),s&&lt.isFunction(a)&&a(s[0]),s=a=t}),"script"):void 0});var Jn,Kn,Qn=0,Zn=e.ActiveXObject&&function(){var e;for(e in Jn)Jn[e](t,!0)};lt.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&$()||M()}:$,Kn=lt.ajaxSettings.xhr(),lt.support.cors=!!Kn&&"withCredentials"in Kn,Kn=lt.support.ajax=!!Kn,Kn&&lt.ajaxTransport(function(n){if(!n.crossDomain||lt.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,f;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=lt.noop,Zn&&delete Jn[a]),i)4!==u.readyState&&u.abort();else{f={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(f.text=u.responseText);try{c=u.statusText}catch(p){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=f.text?200:404}}catch(d){i||o(-1,d)}f&&o(s,c,f,l)},n.async?4===u.readyState?setTimeout(r):(a=++Qn,Zn&&(Jn||(Jn={},lt(e).unload(Zn)),Jn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var er,tr,nr=/^(?:toggle|show|hide)$/,rr=new RegExp("^(?:([+-])=|)("+ct+")([a-z%]*)$","i"),ir=/queueHooks$/,or=[R],ar={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=rr.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(lt.cssNumber[e]?"":"px"),"px"!==r&&s){s=lt.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,lt.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}]};lt.Animation=lt.extend(P,{tweener:function(e,t){lt.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,r=0,i=e.length;i>r;r++)n=e[r],ar[n]=ar[n]||[],ar[n].unshift(t)},prefilter:function(e,t){t?or.unshift(e):or.push(e)}}),lt.Tween=W,W.prototype={constructor:W,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||(lt.cssNumber[n]?"":"px")},cur:function(){var e=W.propHooks[this.prop];return e&&e.get?e.get(this):W.propHooks._default.get(this)},run:function(e){var t,n=W.propHooks[this.prop];return this.pos=t=this.options.duration?lt.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):W.propHooks._default.set(this),this}},W.prototype.init.prototype=W.prototype,W.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=lt.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){lt.fx.step[e.prop]?lt.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[lt.cssProps[e.prop]]||lt.cssHooks[e.prop])?lt.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},W.propHooks.scrollTop=W.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},lt.each(["toggle","show","hide"],function(e,t){var n=lt.fn[t];lt.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(X(t,!0),e,r,i)}}),lt.fn.extend({fadeTo:function(e,t,n,r){return this.filter(C).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=lt.isEmptyObject(e),o=lt.speed(t,n,r),a=function(){var t=P(this,lt.extend({},e),o);a.finish=function(){t.stop(!0)},(i||lt._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=lt.timers,a=lt._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&ir.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)&&lt.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=lt._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=lt.timers,a=r?r.length:0;for(n.finish=!0,lt.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})}}),lt.each({slideDown:X("show"),slideUp:X("hide"),slideToggle:X("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){lt.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),lt.speed=function(e,t,n){var r=e&&"object"==typeof e?lt.extend({},e):{complete:n||!n&&t||lt.isFunction(e)&&e,duration:e,easing:n&&t||t&&!lt.isFunction(t)&&t};return r.duration=lt.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in lt.fx.speeds?lt.fx.speeds[r.duration]:lt.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){lt.isFunction(r.old)&&r.old.call(this),r.queue&&lt.dequeue(this,r.queue)},r},lt.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},lt.timers=[],lt.fx=W.prototype.init,lt.fx.tick=function(){var e,n=lt.timers,r=0;for(er=lt.now();r<n.length;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||lt.fx.stop(),er=t},lt.fx.timer=function(e){e()&&lt.timers.push(e)&&lt.fx.start()},lt.fx.interval=13,lt.fx.start=function(){tr||(tr=setInterval(lt.fx.tick,lt.fx.interval))},lt.fx.stop=function(){clearInterval(tr),tr=null},lt.fx.speeds={slow:600,fast:200,_default:400},lt.fx.step={},lt.expr&&lt.expr.filters&&(lt.expr.filters.animated=function(e){return lt.grep(lt.timers,function(t){return e===t.elem}).length}),lt.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){lt.offset.setOffset(this,e,t)});var n,r,i={top:0,left:0},o=this[0],a=o&&o.ownerDocument;if(a)return n=a.documentElement,lt.contains(n,o)?(typeof o.getBoundingClientRect!==V&&(i=o.getBoundingClientRect()),r=z(a),{top:i.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:i.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):i},lt.offset={setOffset:function(e,t,n){var r=lt.css(e,"position");"static"===r&&(e.style.position="relative");var i,o,a=lt(e),s=a.offset(),u=lt.css(e,"top"),l=lt.css(e,"left"),c=("absolute"===r||"fixed"===r)&&lt.inArray("auto",[u,l])>-1,f={},p={};c?(p=a.position(),i=p.top,o=p.left):(i=parseFloat(u)||0,o=parseFloat(l)||0),lt.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(f.top=t.top-s.top+i),null!=t.left&&(f.left=t.left-s.left+o),"using"in t?t.using.call(e,f):a.css(f)}},lt.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===lt.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),lt.nodeName(e[0],"html")||(n=e.offset()),n.top+=lt.css(e[0],"borderTopWidth",!0),n.left+=lt.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-lt.css(r,"marginTop",!0),left:t.left-n.left-lt.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||G.documentElement;e&&!lt.nodeName(e,"html")&&"static"===lt.css(e,"position");)e=e.offsetParent;return e||G.documentElement})}}),lt.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);lt.fn[e]=function(i){return lt.access(this,function(e,i,o){var a=z(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?lt(a).scrollLeft():o,r?o:lt(a).scrollTop()):e[i]=o,void 0)},e,i,arguments.length,null)}}),lt.each({Height:"height",Width:"width"},function(e,n){lt.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){lt.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return lt.access(this,function(n,r,i){var o;return lt.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?lt.css(n,r,s):lt.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=lt,"function"==typeof n&&n.amd&&n.amd.jQuery&&n("jquery",[],function(){return lt})}(window),n("class",["jquery"],function(e){var t=!1,n=/xyz/.test(function(){})?/\b_super\b/:/.*/,r=function(){}; return r._extend=function(e){function r(){!t&&this.init&&this.init.apply(this,arguments)}var i=this.prototype;t=!0;var o=new this;t=!1;for(var a in e)o[a]="function"==typeof e[a]&&"function"==typeof i[a]&&n.test(e[a])?function(e,t){return function(){var n=this._super;this._super=i[e];var r=t.apply(this,arguments);return this._super=n,r}}(a,e[a]):e[a];return r.prototype=o,r.prototype.constructor=r,r._extend=arguments.callee,r},r=r._extend({bind:function(t,n,r){return e(this).on(t,n,r)},unbind:function(t,n){return e(this).off(t,n,data)},trigger:function(t,n){var r=e.Event(t);return e(this).trigger(r,n),r}})}),n("lego",["jquery","class"],function(e,t){var n=t._extend({defaultOptions:{},init:function(t,n){this.$el=e(t),this.options=e.extend({},this.defaultOptions,n)},trigger:function(t,n){e(this).trigger(t,n)},on:function(t,n){e(this).on(t,n)}});return n.extend=function(t){t.defaultOptions=e.extend({},this.prototype.defaultOptions,t.defaultOptions);var r=this._extend(t);return r.extend=n.extend,r},n}),n("drag-tracker",["lego"],function(e){var t=e.extend({defaultOptions:{dragThreshold:5,ignoreX:!1,ignoreY:!1,dragStart:null,dragUpdate:null,dragStop:null,startEvent:"mousedown",updateEvent:"mousemove",stopEvent:"mouseup"},init:function(e,t){this._super(e,t);var n=this,r=this.$el,i=this.options;this.dragStarted=!1,this.startX=0,this.startY=0,this.mdFunc=function(e,t){return n._startDrag(e,t)},this.mmFunc=function(e,t){return n._handleDrag(e,t)},this.muFunc=function(e,t){return n._stopDrag(e,t)},r.on(i.startEvent,this.mdFunc)},dragStart:function(e,t){var n=this.options;n.dragStart&&n.dragStart(this,e,t)},dragUpdate:function(e,t){var n=this.options;n.dragUpdate&&n.dragUpdate(this,e,t)},dragStop:function(e,t){var n=this.options;n.dragStop&&n.dragStop(this,e,t)},_startDrag:function(e){return this.dragStarted=!1,this.startX=e.pageX,this.startY=e.pageY,this._installDragHandlers(),!1},_handleDrag:function(e){var t=e.pageX-this.startX,n=e.pageY-this.startY,r=this.options;if(!this.dragStarted){if(!r.ignoreX&&Math.abs(t)<r.dragThreshold&&!r.ignoreY&&Math.abs(n)<r.dragThreshold)return!1;this.dragStarted=!0,this.dragStart(0,0)}return this.dragUpdate(r.ignoreX?0:t,r.ignoreY?0:n),!1},_stopDrag:function(e){var t=this.options;if(this._removeDragHandlers(),this.dragStarted){var n=e.pageX-this.startX,r=e.pageY-this.startY;this.dragStop(t.ignoreX?0:n,t.ignoreY?0:r)}return this.dragStarted=!1,!1},_installDragHandlers:function(){var e=this.options;$(document).on(e.updateEvent,this.mmFunc).on(e.stopEvent,this.muFunc)},_removeDragHandlers:function(){var e=this.options;$(document).off(e.updateEvent,this.mmFunc).off(e.stopEvent,this.muFunc)}});return t}),n("draggable",["drag-tracker"],function(e){var t=e.extend({defaultOptions:{dragThreshold:5,ignoreX:!1,ignoreY:!1,dragStart:null,dragUpdate:null,dragStop:null,startEvent:"mousedown",updateEvent:"mousemove",stopEvent:"mouseup",useTransforms:!1},init:function(e,t){this._super(e,t)},dragStart:function(e,t){var n=this.options;this.startTop=parseInt(this.$el.css("top")),this.startLeft=parseInt(this.$el.css("left")),this.setPosition(n.ignoreX?null:this.startLeft+e,n.ignoreY?null:this.startTop+t)},dragUpdate:function(e,t){var n=this.options;this.setPosition(n.ignoreX?null:this.startLeft+e,n.ignoreY?null:this.startTop+t)},dragStop:function(e,t){this.dragUpdate(e,t)},setPosition:function(e,t){var n=this.$el;this.options.useTransforms?(transform=(e?"translateX("+e+") ":"")+(t?"translateY("+t+")":""),n.css({"-webkit-transform":transform,"-moz-transform":transform,"-ms-transform":transform,"-o-transform":transform,transform:transform})):n.css({left:e,top:t})}});return t}),n("radio-group",["lego"],function(e){var t=e.extend({defaultOptions:{activeClass:"active",activeEvent:"click"},init:function(e,t){this._super(e,t);var n=this,r=this.$el,i=this.options;r.on(i.activeEvent,function(e){e.preventDefault(),n._handleActiveEvent($(this))})},_handleActiveEvent:function(e){this.deactivate(),this.activate(e),this.trigger("lego-radio-activate",e[0])},deactivate:function(e){e=e||this.$el,e.removeClass(this.options.activeClass)},activate:function(e){e.addClass(this.options.activeClass)}});return t}),n("tabs",["radio-group"],function(e){var t=e.extend({defaultOptions:{activeClass:"active",activePanelClass:"active",activeEvent:"click",panelSelector:".panel",panelGroups:[]},init:function(e,t){this._super(e,t),this.$panels=$(this.options.panelSelector)},deactivate:function(e){this._super(e),this.$panels.removeClass(this.options.activePanelClass)},activate:function(e){this._super(e),$(e.attr("href")).addClass(this.options.activePanelClass)}});return t}),n("panel-group",["radio-group"],function(e){var t=e.extend({defaultOptions:{activeClass:"active",tabGroups:[]},init:function(e,t){this._super(e,t);var n=this.options,r=n.tabGroups;this.tabGroups=[],this.addTabGroup(r)},addTabGroup:function(e){$.isArray(e)||(e=[e]);for(var t=this,n=function(e,n){t._handleTabSelect(e,n)},r=0,i=e.length;i>r;r++){var o=e[r];this.tabGroups.push(o),o.on("lego-radio-activate",n)}},_handleTabSelect:function(e,t){this.deactivate();var n=this,r=$(t).attr("href").replace(/^#/,""),i=$('[data-id="'+r+'"]');i.each(function(){var e=$(this);-1!=n.$el.index(e)&&n.activate(e)})}});return t}),n("numeric-spinner",["lego","drag-tracker"],function(e,t){var n=e.extend({defaultOptions:{buttonsSelector:".buttons",upButtonSelector:".up.button",downButtonSelector:".down.button",inputSelector:".numeric-input",incrementKeyCodes:[38],decrementKeyCodes:[40],pressAndHoldInterval:100},init:function(e,n){this._super(e,n);var r=this,n=this.options,i=this.options.incrementKeyCodes,o=this.options.decrementKeyCodes;this.intervalId=0,this.$buttons=this.$el.find(n.buttonsSelector),this.$up=this.$buttons.find(n.upButtonSelector),this.$down=this.$buttons.find(n.downButtonSelector),this.$input=this.$el.find(n.inputSelector),this.value=0;new t(this.$buttons,{ignoreX:!0,dragStart:function(){r.value=parseInt(r.$input.val())||0},dragUpdate:function(e,t,n){r.$input.val(Math.floor(r.value-n/3))}});this.$input.on("keydown",function(e){-1!=i.indexOf(e.which)?(e.preventDefault(),r._incrementValue()):-1!=o.indexOf(e.which)&&(e.preventDefault(),r._decrementValue())}),this.$up.on("click",function(e){e.preventDefault(),r._incrementValue()}),this.$down.on("click",function(e){e.preventDefault(),r._decrementValue()}),this.$up.on("mousedown",function(){r.intervalID=setInterval(function(){r._incrementValue()},r.options.pressAndHoldInterval)}).on("mouseup mouseleave",function(){clearInterval(r.intervalID)}),this.$down.on("mousedown",function(){r.intervalID=setInterval(function(){r._decrementValue()},r.options.pressAndHoldInterval)}).on("mouseup mouseleave",function(){clearInterval(r.intervalID)})},_decrementValue:function(){var e=parseInt(this.$input.val())||0;this.$input.val(e-1)},_incrementValue:function(){var e=parseInt(this.$input.val())||0;this.$input.val(e+1)}});return n}),n("namespace",["lego","drag-tracker","draggable","radio-group","tabs","panel-group","numeric-spinner"],function(e,t,n,r,i,o,a){return e.DragTracker=t,e.Draggable=n,e.RadioGroup=r,e.Tabs=i,e.PanelGroup=o,e.NumericSpinner=a,e}),t("namespace")});
src/routes/profile/Profile.js
devcharleneg/twitter-react-app
import React from 'react'; import Twit from 'twit'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Profile.css'; import AppConstants from '../../constants/AppConstants'; import request from 'superagent'; import Tweet from 'react-tweet' import {Row,Col,FormGroup,FormControl,ControlLabel,Button,Glyphicon} from 'react-bootstrap'; import Session from '../../core/Session'; import UserTimeline from '../../components/Tweet/UserTimeline'; import UserInfo from '../../components/Profile/UserInfo'; class Profile extends React.Component { static propTypes = { title: PropTypes.string.isRequired }; constructor(props) { super(props); } render() { return ( <div className={s.root}> <div className={s.container}> <Row> <Col sm={4}> <UserInfo /> </Col> <Col sm={8}> <UserTimeline /> </Col> </Row> </div> </div> ); } } export default withStyles(s)(Profile);
app/javascript/mastodon/features/compose/components/character_counter.js
mstdn-jp/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { length } from 'stringz'; export default class CharacterCounter extends React.PureComponent { static propTypes = { text: PropTypes.string.isRequired, max: PropTypes.number.isRequired, }; checkRemainingText (diff) { if (diff < 0) { return <span className='character-counter character-counter--over'>{diff}</span>; } return <span className='character-counter'>{diff}</span>; } render () { const diff = this.props.max - length(this.props.text); return this.checkRemainingText(diff); } }
themes/genius/Genius 2.3.1 Bootstrap 4/React_Full_Project/src/index.js
davidchristie/kaenga-housing-calculator
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, hashHistory } from 'react-router'; import routes from './routes'; ReactDOM.render( <Router routes={routes} history={hashHistory} />, document.getElementById('root') );
src/renderers/dom/shared/eventPlugins/__tests__/SelectEventPlugin-test.js
eoin/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 ReactDOMComponentTree; var ReactTestUtils; var SelectEventPlugin; describe('SelectEventPlugin', () => { function extract(node, topLevelEvent) { return SelectEventPlugin.extractEvents( topLevelEvent, ReactDOMComponentTree.getInstanceFromNode(node), {target: node}, node ); } beforeEach(() => { React = require('React'); ReactDOM = require('ReactDOM'); ReactDOMComponentTree = require('ReactDOMComponentTree'); ReactTestUtils = require('ReactTestUtils'); SelectEventPlugin = require('SelectEventPlugin'); }); it('should skip extraction if no listeners are present', () => { class WithoutSelect extends React.Component { render() { return <input type="text" />; } } var rendered = ReactTestUtils.renderIntoDocument(<WithoutSelect />); var node = ReactDOM.findDOMNode(rendered); node.focus(); var mousedown = extract(node, 'topMouseDown'); expect(mousedown).toBe(null); var mouseup = extract(node, 'topMouseUp'); expect(mouseup).toBe(null); }); it('should extract if an `onSelect` listener is present', () => { class WithSelect extends React.Component { render() { return <input type="text" onSelect={this.props.onSelect} />; } } var cb = jest.fn(); var rendered = ReactTestUtils.renderIntoDocument( <WithSelect onSelect={cb} /> ); var node = ReactDOM.findDOMNode(rendered); node.selectionStart = 0; node.selectionEnd = 0; node.focus(); var focus = extract(node, 'topFocus'); expect(focus).toBe(null); var mousedown = extract(node, 'topMouseDown'); expect(mousedown).toBe(null); var mouseup = extract(node, 'topMouseUp'); expect(mouseup).not.toBe(null); expect(typeof mouseup).toBe('object'); expect(mouseup.type).toBe('select'); expect(mouseup.target).toBe(node); }); });
blueocean-material-icons/src/js/components/svg-icons/navigation/arrow-drop-down.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const NavigationArrowDropDown = (props) => ( <SvgIcon {...props}> <path d="M7 10l5 5 5-5z"/> </SvgIcon> ); NavigationArrowDropDown.displayName = 'NavigationArrowDropDown'; NavigationArrowDropDown.muiName = 'SvgIcon'; export default NavigationArrowDropDown;
docs/app/Examples/behaviors/Visibility/Types/index.js
aabustamante/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const VisibilityExample = () => ( <ExampleSection title='Types'> <ComponentExample title='Default' description='An example of Visibility' examplePath='behaviors/Visibility/Types/VisibilityExample' /> </ExampleSection> ) export default VisibilityExample
ajax/libs/vue/1.0.26/vue.js
tholu/cdnjs
/*! * Vue.js v1.0.26 * (c) 2016 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'; 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) { if (obj._isVue) { delete obj._data[key]; obj._digest(); } 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(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 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]'; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; // UA sniffing for working around browser-specific quirks var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && UA.indexOf('trident') > 0; var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isAndroid = UA && UA.indexOf('android') > 0; var isIos = UA && /(iphone|ipad|ipod|ios)/i.test(UA); var iosVersionMatch = isIos && UA.match(/os ([\d_]+)/); var iosVersion = iosVersionMatch && iosVersionMatch[1].split('_'); // detecting iOS UIWebView by indexedDB var hasMutationObserverBug = iosVersion && Number(iosVersion[0]) >= 9 && Number(iosVersion[1]) >= 3 && !window.indexedDB; 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' && !hasMutationObserverBug) { 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 { // webpack attempts to inject a shim for setImmediate // if it is used as a global, so we have to work around that to // avoid bundling unnecessary code. var context = inBrowser ? window : typeof global !== 'undefined' ? global : {}; timerFunc = context.setImmediate || setTimeout; } return function (cb, ctx) { var func = ctx ? function () { cb.call(ctx); } : cb; callbacks.push(func); if (pending) return; pending = true; timerFunc(nextTickHandler, 0); }; })(); var _Set = undefined; /* istanbul ignore if */ if (typeof Set !== 'undefined' && Set.toString().match(/native code/)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = function () { this.set = Object.create(null); }; _Set.prototype.has = function (key) { return this.set[key] !== undefined; }; _Set.prototype.add = function (key) { this.set[key] = 1; }; _Set.prototype.clear = function () { this.set = Object.create(null); }; } 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 removed; var entry = this.get(key, true); if (!entry) { if (this.size === this.limit) { removed = this.shift(); } entry = { key: key }; this._keymap[key] = entry; if (this.tail) { this.tail.newer = entry; entry.older = this.tail; } else { this.head = entry; } this.tail = entry; this.size++; } entry.value = value; return removed; }; /** * 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; this.size--; } 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} s * @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 + '((?:.|\\n)+?)' + unsafeClose + '|' + open + '((?:.|\\n)+?)' + close, 'g'); htmlRE = new RegExp('^' + unsafeOpen + '((?:.|\\n)+?)' + 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; } 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 * @param {Vue} [vm] * @return {String} */ function tokensToExp(tokens, vm) { if (tokens.length > 1) { return tokens.map(function (token) { return formatToken(token, vm); }).join('+'); } else { return formatToken(tokens[0], vm, true); } } /** * Format a single token. * * @param {Object} token * @param {Vue} [vm] * @param {Boolean} [single] * @return {String} */ function formatToken(token, vm, single) { return token.tag ? token.oneTime && vm ? '"' + vm.$eval(token.value) + '"' : 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 = /[^|]\|[^|]/; function inlineFilters(exp, single) { if (!filterRE.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 = 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 to allow devtools inspection. * Disabled by default in production builds. */ devtools: 'development' !== 'production', /** * 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; var formatComponentName = undefined; if ('development' !== 'production') { (function () { var hasConsole = typeof console !== 'undefined'; warn = function (msg, vm) { if (hasConsole && !config.silent) { console.error('[Vue warn]: ' + msg + (vm ? formatComponentName(vm) : '')); } }; formatComponentName = function (vm) { var name = vm._isVue ? vm.$options.name : vm.name; return name ? ' (found in component: <' + hyphenate(name) + '>)' : ''; }; })(); } /** * 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); } var transition = Object.freeze({ appendWithTransition: appendWithTransition, beforeWithTransition: beforeWithTransition, removeWithTransition: removeWithTransition, applyTransition: applyTransition }); /** * 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) { if (!node) return false; var doc = node.ownerDocument.documentElement; var parent = 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 * @param {Boolean} [useCapture] */ function on(el, event, cb, useCapture) { el.addEventListener(event, cb, useCapture); } /** * Remove event listener shorthand. * * @param {Element} el * @param {String} event * @param {Function} cb */ function off(el, event, cb) { el.removeEventListener(event, cb); } /** * For IE9 compat: when both class and :class are present * getAttribute('class') returns wrong value... * * @param {Element} el * @return {String} */ function getClass(el) { var classname = el.className; if (typeof classname === 'object') { classname = classname.baseVal || ''; } return classname; } /** * 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 && !/svg$/.test(el.namespaceURI)) { 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 = ' ' + getClass(el) + ' '; 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 = ' ' + getClass(el) + ' '; 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|DocumentFragment} */ function extractContent(el, asFragment) { var child; var rawContent; /* istanbul ignore if */ if (isTemplate(el) && isFragment(el.content)) { 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 text and comment * nodes inside a parent. * * @param {Node} node */ function trimNode(node) { var child; /* eslint-disable no-sequences */ while ((child = node.firstChild, isTrimmable(child))) { node.removeChild(child); } while ((child = node.lastChild, isTrimmable(child))) { node.removeChild(child); } /* eslint-enable no-sequences */ } function isTrimmable(node) { return node && (node.nodeType === 3 && !node.data.trim() || node.nodeType === 8); } /** * 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.__v_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(); } } } /** * Check if a node is a DocumentFragment. * * @param {Node} node * @return {Boolean} */ function isFragment(node) { return node && node.nodeType === 11; } /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. * * @param {Element} el * @return {String} */ function getOuterHTML(el) { if (el.outerHTML) { return el.outerHTML; } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML; } } 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)$/i; var reservedTagRE = /^(slot|partial|component)$/i; var isUnknownElement = undefined; if ('development' !== 'production') { isUnknownElement = function (el, tag) { if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement; } else { return (/HTMLUnknownElement/.test(el.toString()) && // Chrome returns unknown for several HTML5 elements. // https://code.google.com/p/chromium/issues/detail?id=540526 // Firefox returns unknown for some "Interactive elements." !/^(data|time|rtc|rb|details|dialog|summary)$/.test(tag) ); } }; } /** * 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, options); if (is) { return is; } else if ('development' !== 'production') { var expectedTag = options._componentNameMap && options._componentNameMap[tag]; if (expectedTag) { warn('Unknown custom element: <' + tag + '> - ' + 'did you mean <' + expectedTag + '>? ' + 'HTML is case-insensitive, remember to use kebab-case in templates.'); } else if (isUnknownElement(el, tag)) { warn('Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.'); } } } } else if (hasAttrs) { return getIsBinding(el, options); } } /** * Get "is" binding from an element. * * @param {Element} el * @param {Object} options * @return {Object|undefined} */ function getIsBinding(el, options) { // dynamic syntax var exp = el.getAttribute('is'); if (exp != null) { if (resolveAsset(options, 'components', exp)) { el.removeAttribute('is'); return { id: exp }; } } else { exp = getBindAttr(el, 'is'); if (exp != null) { return { id: exp, dynamic: true }; } } } /** * 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.', vm); 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.', vm); 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 = strats.activate = function (parentVal, childVal) { return childVal ? parentVal ? parentVal.concat(childVal) : isArray(childVal) ? childVal : [childVal] : parentVal; }; /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets(parentVal, childVal) { var res = Object.create(parentVal || null); return childVal ? extend(res, 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 ids = Object.keys(components); var def; if ('development' !== 'production') { var map = options._componentNameMap = {}; } 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; } // record a all lowercase <-> kebab-case mapping for // possible custom element case error warning if ('development' !== 'production') { map[key.replace(/-/g, '').toLowerCase()] = hyphenate(key); } 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); if ('development' !== 'production') { if (child.propsData && !vm) { warn('propsData can only be used as an instantiation option.'); } } var options = {}; var key; if (child['extends']) { parent = typeof child['extends'] === 'function' ? mergeOptions(parent, child['extends'].options, vm) : mergeOptions(parent, child['extends'], vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { var mixin = child.mixins[i]; var mixinOptions = mixin.prototype instanceof Vue ? mixin.options : mixin; parent = mergeOptions(parent, mixinOptions, 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 * @param {Boolean} warnMissing * @return {Object|Function} */ function resolveAsset(options, type, id, warnMissing) { /* istanbul ignore if */ if (typeof id !== 'string') { return; } var assets = options[type]; var camelizedId; var res = assets[id] || // camelCase ID assets[camelizedId = camelize(id)] || // Pascal Case ID assets[camelizedId.charAt(0).toUpperCase() + camelizedId.slice(1)]; if ('development' !== 'production' && warnMissing && !res) { warn('Failed to resolve ' + type.slice(0, -1) + ': ' + id, options); } return res; } var uid$1 = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. * * @constructor */ function Dep() { this.id = uid$1++; 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 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 or target element reference. * * @param {*} item */ 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 arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * By default, when a reactive property is set, the new value is * also converted to become reactive. However in certain cases, e.g. * v-for scope alias and props, we don't want to force conversion * because the value may be a nested value under a frozen data structure. * * So whenever we want to set a reactive property without forcing * conversion on the new value, we wrap that call inside this function. */ var shouldConvert = true; function withoutConversion(fn) { shouldConvert = false; fn(); shouldConvert = true; } /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. * * @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} src */ function protoAugment(target, src) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * 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 (shouldConvert && (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(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return; } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; var childOb = 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, toArray: toArray, extend: extend, isObject: isObject, isPlainObject: isPlainObject, def: def, debounce: _debounce, indexOf: indexOf, cancellable: cancellable, looseEqual: looseEqual, isArray: isArray, hasProto: hasProto, inBrowser: inBrowser, devtools: devtools, isIE: isIE, isIE9: isIE9, isAndroid: isAndroid, isIos: isIos, iosVersionMatch: iosVersionMatch, iosVersion: iosVersion, hasMutationObserverBug: hasMutationObserverBug, get transitionProp () { return transitionProp; }, get transitionEndEvent () { return transitionEndEvent; }, get animationProp () { return animationProp; }, get animationEndEvent () { return animationEndEvent; }, nextTick: nextTick, get _Set () { return _Set; }, query: query, inDoc: inDoc, getAttr: getAttr, getBindAttr: getBindAttr, hasBindAttr: hasBindAttr, before: before, after: after, remove: remove, prepend: prepend, replace: replace, on: on, off: off, setClass: setClass, addClass: addClass, removeClass: removeClass, extractContent: extractContent, trimNode: trimNode, isTemplate: isTemplate, createAnchor: createAnchor, findRef: findRef, mapNodeRange: mapNodeRange, removeNodeRange: removeNodeRange, isFragment: isFragment, getOuterHTML: getOuterHTML, mergeOptions: mergeOptions, resolveAsset: resolveAsset, checkComponentAttr: checkComponentAttr, 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 = this._vForRemoving = 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 _initData(). 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 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, vm) { 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.', vm); }; } /** * 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, last); } 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, obj); } 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,' + 'protected,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 literalValueRE$1 = /^(?:true|false|null|undefined|Infinity|NaN)$/; function noop() {} /** * 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 because 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 { /* eslint-disable no-new-func */ return new Function('scope', 'return ' + body + ';'); /* eslint-enable no-new-func */ } catch (e) { if ('development' !== 'production') { /* istanbul ignore if */ if (e.toString().match(/unsafe-eval|CSP/)) { warn('It seems you are using the default build of Vue.js in an environment ' + 'with Content Security Policy that prohibits unsafe-eval. ' + 'Use the CSP-compliant build instead: ' + 'http://vuejs.org/guide/installation.html#CSP-compliant-build'); } else { warn('Invalid expression. ' + 'Generated function body: ' + body); } } return noop; } } /** * 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 literal values as paths !literalValueRE$1.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; /** * Reset the batcher's state. */ function resetBatcherState() { queue.length = 0; userQueue.length = 0; has = {}; circular = {}; waiting = false; } /** * Flush both queues and run the watchers. */ function flushBatcherQueue() { var _again = true; _function: while (_again) { _again = false; runBatcherQueue(queue); runBatcherQueue(userQueue); // user watchers triggered more watchers, // keep flushing until it depletes if (queue.length) { _again = true; continue _function; } // dev tool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.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) { warn('You may have an infinite update loop for watcher ' + 'with expression "' + watcher.expression + '"', watcher.vm); break; } } } queue.length = 0; } /** * 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) { // 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|Function} expOrFn * @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 = expOrFn; this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.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; } /** * 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 + '": ' + e.toString(), this.vm); } } // "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.toString(), this.vm); } } // 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.', this.vm); 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; }; /** * Add a dependency to this directive. * * @param {Dep} dep */ Watcher.prototype.addDep = function (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.afterGet = function () { Dep.target = null; var i = this.deps.length; while (i--) { var dep = this.deps[i]; if (!this.newDepIds.has(dep.id)) { dep.removeSub(this); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. * * @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 i = this.deps.length; while (i--) { this.deps[i].depend(); } }; /** * Remove self from all dependencies' subcriber list. */ Watcher.prototype.teardown = function () { if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed or is performing a v-for // re-render (the watcher list is then filtered by v-for). if (!this.vm._isBeingDestroyed && !this.vm._vForRemoving) { this.vm._watchers.$remove(this); } var i = this.deps.length; while (i--) { this.deps[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 */ var seenObjects = new _Set(); function traverse(val, seen) { var i = undefined, keys = undefined; if (!seen) { seen = seenObjects; seen.clear(); } var isA = isArray(val); var isO = isObject(val); if ((isA || isO) && Object.isExtensible(val)) { if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return; } else { seen.add(depId); } } if (isA) { i = val.length; while (i--) traverse(val[i], seen); } else if (isO) { keys = Object.keys(val); i = keys.length; while (i--) traverse(val[keys[i]], seen); } } } var text$1 = { bind: function bind() { this.attr = this.el.nodeType === 3 ? 'data' : 'textContent'; }, update: function update(value) { this.el[this.attr] = _toString(value); } }; 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) && isFragment(node.content); } var tagRE$1 = /<([\w:-]+)/; var entityRE = /&#?\w+?;/; var commentRE = /<!--/; /** * 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 cacheKey = raw ? templateString : templateString.trim(); var hit = templateCache.get(cacheKey); if (hit) { return hit; } var frag = document.createDocumentFragment(); var tagMatch = templateString.match(tagRE$1); var entityMatch = entityRE.test(templateString); var commentMatch = commentRE.test(templateString); if (!tagMatch && !entityMatch && !commentMatch) { // 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'); 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); } } if (!raw) { trimNode(frag); } templateCache.put(cacheKey, 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. However, iOS Safari has // bug when using directly cloned template content with touch // events and can cause crashes when the nodes are removed from DOM, so we // have to treat template elements as string templates. (#2805) /* istanbul ignore if */ if (isRealTemplate(node)) { return stringToFragment(node.innerHTML); } // 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) { /* istanbul ignore if */ 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 (isFragment(template)) { 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 }); 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); } }; /** * 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] * @param {Fragment} [parentFrag] */ 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].__v_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.__v_frag = 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.childFrags.length; i < l; i++) { this.childFrags[i].callHook(hook); } for (i = 0, l = this.children.length; i < l; i++) { hook(this.children[i]); } }; /** * 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; this.beforeRemove(); 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); this.beforeRemove(); removeNodeRange(this.node, this.end, this.vm, this.frag, function () { if (shouldCallRemove) { self.callHook(detach); } self.destroy(); }); } /** * Prepare the fragment for removal. */ Fragment.prototype.beforeRemove = function () { var i, l; for (i = 0, l = this.childFrags.length; i < l; i++) { // call the same method recursively on child // fragments, depth-first this.childFrags[i].beforeRemove(false); } for (i = 0, l = this.children.length; i < l; i++) { // 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. this.children[i].$destroy(false, true); } var dirs = this.unlink.dirs; for (i = 0, l = dirs.length; i < l; i++) { // disable the watchers on all the directives // so that the rendered content stays the same // during removal. dirs[i]._watcher && dirs[i]._watcher.teardown(); } }; /** * Destroy the fragment. */ Fragment.prototype.destroy = function () { if (this.parentFrag) { this.parentFrag.childFrags.$remove(this); } this.node.__v_frag = null; this.unlink(); }; /** * Call attach hook for a Vue instance. * * @param {Vue} child */ function attach(child) { if (!child._isAttached && inDoc(child.$el)) { child._callHook('attached'); } } /** * Call detach hook for a Vue instance. * * @param {Vue} child */ function detach(child) { if (child._isAttached && !inDoc(child.$el)) { 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) && !el.hasAttribute('v-if')) { 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 : getOuterHTML(el)); 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 ON = 700; var MODEL = 800; var BIND = 850; var TRANSITION = 1100; var EL = 1500; var COMPONENT = 1500; var PARTIAL = 1750; var IF = 2100; var FOR = 2200; var SLOT = 2300; var uid$3 = 0; var vFor = { priority: FOR, terminal: true, params: ['track-by', 'stagger', 'enter-stagger', 'leave-stagger'], bind: function bind() { // support "item in/of items" syntax var inMatch = this.expression.match(/(.*) (?:in|of) (.*)/); 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('Invalid v-for expression "' + this.descriptor.raw + '": ' + 'alias is required.', this.vm); return; } // uid as a cache identifier this.id = '__v-for__' + ++uid$3; // 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) { withoutConversion(function () { 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; // when removing a large number of fragments, watcher removal // turns out to be a perf bottleneck, so we batch the watcher // removals into a single filter call! this.vm._vForRemoving = true; for (i = 0, l = oldFrags.length; i < l; i++) { frag = oldFrags[i]; if (!frag.reused) { this.deleteCachedFrag(frag); this.remove(frag, removalIndex++, totalRemoved, inDocument); } } this.vm._vForRemoving = false; if (removalIndex) { this.vm._watchers = this.vm._watchers.filter(function (w) { return w.active; }); } // 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 // important: define the scope alias without forced conversion // so that frozen data structures remain non-reactive. withoutConversion(function () { 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.__v_frag = frag; } after(anchor, prevEl); var op = frag.staggerCb = cancellable(function () { frag.staggerCb = null; frag.before(anchor); remove(anchor); }); setTimeout(op, staggerAmount); } else { var target = prevEl.nextSibling; /* istanbul ignore if */ if (!target) { // reset end anchor position in case the position was messed up // by an external drag-n-drop library. after(this.end, prevEl); target = this.end; } frag.before(target); } }, /** * 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) { // fix a common issue with Sortable: // if prevEl doesn't have nextSibling, this means it's // been dragged after the end anchor. Just re-position // the end anchor to the end of the container. /* istanbul ignore if */ if (!prevEl.nextSibling) { this.end.parentNode.appendChild(this.end); } 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 = getTrackByKey(index, key, value, trackByKey); 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 if (Object.isExtensible(value)) { def(value, id, frag); } else if ('development' !== 'production') { warn('Frozen v-for objects cannot be automatically tracked, make sure to ' + 'provide a track-by key.'); } } 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 = getTrackByKey(index, key, value, trackByKey); 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 = getTrackByKey(index, key, value, trackByKey); 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 * watcher'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' && !isNaN(value)) { 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.__v_frag; while ((!frag || frag.forId !== id || !frag.inserted) && el !== anchor) { el = el.previousSibling; /* istanbul ignore if */ if (!el) return; frag = el.__v_frag; } 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(Math.floor(n)); while (++i < n) { ret[i] = i; } return ret; } /** * Get the track by key for an item. * * @param {Number} index * @param {String} key * @param {*} value * @param {String} [trackByKey] */ function getTrackByKey(index, key, value, trackByKey) { return trackByKey ? trackByKey === '$index' ? index : trackByKey.charAt(0).match(/\w/) ? getPath(value, trackByKey) : value[trackByKey] : key || value; } 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.', this.vm); }; } var vIf = { priority: IF, terminal: true, 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.elseEl = next; } // check main block this.anchor = createAnchor('v-if'); replace(el, this.anchor); } else { 'development' !== 'production' && warn('v-if="' + this.expression + '" cannot be ' + 'used on an instance root element.', this.vm); 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; } // lazy init factory if (!this.factory) { this.factory = new FragmentFactory(this.vm, this.el); } 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.elseEl && !this.elseFrag) { if (!this.elseFactory) { this.elseFactory = new FragmentFactory(this.elseEl._context || this.vm, this.elseEl); } 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(); } if (this.elseFrag) { this.elseFrag.destroy(); } } }; 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 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 && !lazy) { 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) { var method = jQuery.fn.on ? 'on' : 'bind'; jQuery(el)[method]('change', this.rawListener); if (!lazy) { jQuery(el)[method]('input', this.listener); } } else { this.on('change', this.rawListener); 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) { // #3029 only update when the value changes. This prevent // browsers from overwriting values like selectionStart value = _toString(value); if (value !== this.el.value) this.el.value = value; }, unbind: function unbind() { var el = this.el; if (this.hasjQuery) { var method = jQuery.fn.off ? 'off' : 'unbind'; jQuery(el)[method]('change', this.listener); jQuery(el)[method]('input', this.listener); } } }; 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 select = { bind: function bind() { var _this = this; 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', function () { nextTick(_this.forceUpdate); }); if (!inDoc(el)) { nextTick(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 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 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="' + this.descriptor.raw + '". ' + 'You might want to use a two-way filter to ensure correct behavior.', this.vm); } 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, this.vm); 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(); } }; // keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, 'delete': [8, 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]; }); codes = [].concat.apply([], codes); 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); }; } function selfFilter(handler) { return function selfHandler(e) { if (e.target === e.currentTarget) { return handler.call(this, e); } }; } var on$1 = { priority: ON, acceptStatement: true, keyCodes: keyCodes, bind: function bind() { // deal with iframes if (this.el.tagName === 'IFRAME' && this.arg !== 'load') { var self = this; this.iframeBind = function () { on(self.el.contentWindow, self.arg, self.handler, self.modifiers.capture); }; 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, this.vm); return; } // apply modifiers if (this.modifiers.stop) { handler = stopFilter(handler); } if (this.modifiers.prevent) { handler = preventFilter(handler); } if (this.modifiers.self) { handler = selfFilter(handler); } // key filter var keys = Object.keys(this.modifiers).filter(function (key) { return key !== 'stop' && key !== 'prevent' && key !== 'self' && key !== 'capture'; }); if (keys.length) { handler = keyFilter(handler, keys); } this.reset(); this.handler = handler; if (this.iframeBind) { this.iframeBind(); } else { on(this.el, this.arg, this.handler, this.modifiers.capture); } }, 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 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) { /* istanbul ignore if */ if ('development' !== 'production') { warn('It\'s probably a bad idea to use !important with inline rules. ' + 'This feature will be deprecated in a future version of Vue.'); } value = value.replace(importantRE, '').trim(); this.el.style.setProperty(prop.kebab, value, isImportant); } else { this.el.style[prop.camel] = value; } } else { this.el.style[prop.camel] = ''; } } }; /** * 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'); } var i = prefixes.length; var prefixed; if (camel !== 'filter' && camel in testEl.style) { return { kebab: prop, camel: camel }; } while (i--) { prefixed = camelPrefixes[i] + upper; if (prefixed in testEl.style) { return { kebab: prefixes[i] + prop, camel: prefixed }; } } } // 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 expect enumrated values of "true" or "false" // but are not boolean attributes var enumeratedAttrRE = /^(?:draggable|contenteditable|spellcheck)$/; // 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$1 = { 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 var descriptor = this.descriptor; var tokens = descriptor.interp; if (tokens) { // handle interpolations with one-time tokens if (descriptor.hasOneTime) { this.expression = tokensToExp(tokens, this._scope || this.vm); } // only allow binding on native attributes if (disallowedInterpAttrRE.test(attr) || attr === 'name' && (tag === 'PARTIAL' || tag === 'SLOT')) { 'development' !== 'production' && warn(attr + '="' + descriptor.raw + '": ' + 'attribute interpolation is not allowed in Vue.js ' + 'directives and special attributes.', this.vm); this.el.removeAttribute(attr); this.invalid = true; } /* istanbul ignore if */ if ('development' !== 'production') { var raw = attr + '="' + descriptor.raw + '": '; // warn src if (attr === 'src') { warn(raw + 'interpolation in "src" attribute will cause ' + 'a 404 request. Use v-bind:src instead.', this.vm); } // 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.', this.vm); } } } }, 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 (this.modifiers.camel) { attr = camelize(attr); } if (!interp && attrWithPropsRE.test(attr) && attr in el) { var attrValue = attr === 'value' ? value == null // IE9 will set input.value to "null" for null... ? '' : value : value; if (el[attr] !== attrValue) { el[attr] = attrValue; } } // 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 (enumeratedAttrRE.test(attr)) { el.setAttribute(attr, value ? 'true' : 'false'); } else 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 === true ? '' : value); } else { el.setAttribute(attr, value === true ? '' : value); } } else { el.removeAttribute(attr); } } }; 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 ref = { bind: function bind() { 'development' !== 'production' && warn('v-ref:' + this.arg + ' must be used on a child ' + 'component. Found on <' + this.el.tagName.toLowerCase() + '>.', this.vm); } }; var cloak = { bind: function bind() { var el = this.el; this.vm.$once('pre-hook:compiled', function () { el.removeAttribute('v-cloak'); }); } }; // must export plain object var directives = { text: text$1, html: html, 'for': vFor, 'if': vIf, show: show, model: model, on: on$1, bind: bind$1, el: el, ref: ref, cloak: cloak }; var vClass = { deep: true, update: function update(value) { if (!value) { this.cleanup(); } else if (typeof value === 'string') { this.setClass(value.trim().split(/\s+/)); } else { this.setClass(normalize$1(value)); } }, setClass: function setClass(value) { this.cleanup(value); for (var i = 0, l = value.length; i < l; i++) { var val = value[i]; if (val) { apply(this.el, val, addClass); } } this.prevKeys = value; }, cleanup: function cleanup(value) { var prevKeys = this.prevKeys; if (!prevKeys) return; var i = prevKeys.length; while (i--) { var key = prevKeys[i]; if (!value || value.indexOf(key) < 0) { apply(this.el, key, removeClass); } } } }; /** * Normalize objects and arrays (potentially containing objects) * into array of strings. * * @param {Object|Array<String|Object>} value * @return {Array<String>} */ function normalize$1(value) { var res = []; if (isArray(value)) { for (var i = 0, l = value.length; i < l; i++) { var _key = value[i]; if (_key) { if (typeof _key === 'string') { res.push(_key); } else { for (var k in _key) { if (_key[k]) res.push(k); } } } } } else if (isObject(value)) { for (var key in value) { if (value[key]) res.push(key); } } return res; } /** * Add or remove a class/classes on an element * * @param {Element} el * @param {String} key The class name. This may or may not * contain a space character, in such a * case we'll deal with multiple class * names at once. * @param {Function} fn */ function apply(el, key, fn) { key = key.trim(); if (key.indexOf(' ') === -1) { fn(el, key); return; } // The key contains one or more space characters. // Since a class name doesn't accept such characters, we // treat it as multiple classes. var keys = key.split(/\s+/); for (var i = 0, l = keys.length; i < l; i++) { fn(el, keys[i]); } } 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'); 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. * * @param {String|Function} value * @param {Function} cb */ resolveComponent: function resolveComponent(value, cb) { var self = this; this.pendingComponentCb = cancellable(function (Component) { self.ComponentName = Component.options.name || (typeof value === 'string' ? value : null); self.Component = Component; cb(); }); this.vm._resolveComponent(value, 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 activateHooks = this.Component.options.activate; var cached = this.getCached(); var newComponent = this.build(); if (activateHooks && !cached) { this.waitingFor = newComponent; callActivateHooks(activateHooks, 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, child); } 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) { if (!this.keepAlive) { this.waitingFor.$destroy(); } this.waitingFor = null; } var child = this.childVM; if (!child || this.keepAlive) { if (child) { // remove ref child._inactive = true; 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 (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; } } }; /** * Call activate hooks in order (asynchronous) * * @param {Array} hooks * @param {Vue} vm * @param {Function} cb */ function callActivateHooks(hooks, vm, cb) { var total = hooks.length; var called = 0; hooks[0].call(vm, next); function next() { if (++called >= total) { cb(); } else { hooks[called].call(vm, next); } } } 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 * @param {Vue} vm * @return {Function} propsLinkFn */ function compileProps(el, propOptions, vm) { 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.', vm); 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.', vm); 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) && !parsed.filters) { // 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, vm); } } 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.', vm); } } else if ((value = getAttr(el, attr)) !== null) { // has literal binding! prop.raw = value; } else if ('development' !== 'production') { // check possible camelCase prop usage var lowerCaseName = path.toLowerCase(); value = /[A-Z\-]/.test(name) && (el.getAttribute(lowerCaseName) || el.getAttribute(':' + lowerCaseName) || el.getAttribute('v-bind:' + lowerCaseName) || el.getAttribute(':' + lowerCaseName + '.once') || el.getAttribute('v-bind:' + lowerCaseName + '.once') || el.getAttribute(':' + lowerCaseName + '.sync') || el.getAttribute('v-bind:' + lowerCaseName + '.sync')); if (value) { warn('Possible usage error for prop `' + lowerCaseName + '` - ' + 'did you mean `' + attr + '`? HTML is case-insensitive, remember to use ' + 'kebab-case for props in templates.', vm); } else if (options.required) { // warn missing required warn('Missing required prop: ' + name, vm); } } // 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 inlineProps = vm.$options.propsData; 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 (inlineProps && hasOwn(inlineProps, path)) { initProp(vm, prop, inlineProps[path]); }if (raw === null) { // initialize absent prop initProp(vm, prop, undefined); } else if (prop.dynamic) { // dynamic prop if (prop.mode === propBindingModes.ONE_TIME) { // one time binding value = (scope || vm._context || vm).$get(prop.parentPath); initProp(vm, prop, value); } else { if (vm._context) { // dynamic binding vm._bindDir({ name: 'prop', def: propDef, prop: prop }, null, null, scope); // el, host, scope } else { // root instance initProp(vm, prop, vm.$get(prop.parentPath)); } } } 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, or with same // literal value (e.g. disabled="disabled") // see https://github.com/vuejs/vue-loader/issues/182 value = options.type === Boolean && (raw === '' || raw === hyphenate(prop.name)) ? true : raw; initProp(vm, prop, value); } } }; } /** * Process a prop with a rawValue, applying necessary coersions, * default values & assertions and call the given callback with * processed value. * * @param {Vue} vm * @param {Object} prop * @param {*} rawValue * @param {Function} fn */ function processPropValue(vm, prop, rawValue, fn) { var isSimple = prop.dynamic && isSimplePath(prop.parentPath); var value = rawValue; if (value === undefined) { value = getPropDefaultValue(vm, prop); } value = coerceProp(prop, value, vm); var coerced = value !== rawValue; if (!assertProp(prop, value, vm)) { value = undefined; } if (isSimple && !coerced) { withoutConversion(function () { fn(value); }); } else { fn(value); } } /** * 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) { processPropValue(vm, prop, value, function (value) { defineReactive(vm, prop.path, value); }); } /** * Update a prop's value on a vm. * * @param {Vue} vm * @param {Object} prop * @param {*} value */ function updateProp(vm, prop, value) { processPropValue(vm, prop, value, function (value) { vm[prop.path] = value; }); } /** * Get the default value of a prop. * * @param {Vue} vm * @param {Object} prop * @return {*} */ function getPropDefaultValue(vm, prop) { // no default, return undefined var options = prop.options; 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('Invalid default value for prop "' + prop.name + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm); } // call factory function for non-Function types return typeof def === 'function' && options.type !== Function ? def.call(vm) : def; } /** * Assert whether a prop is valid. * * @param {Object} prop * @param {*} value * @param {Vue} vm */ function assertProp(prop, value, vm) { if (!prop.options.required && ( // non-required prop.raw === null || // abscent value == null) // null or undefined ) { return true; } var options = prop.options; var type = options.type; var valid = !type; var expectedTypes = []; if (type) { if (!isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType); valid = assertedType.valid; } } if (!valid) { if ('development' !== 'production') { warn('Invalid prop: type check failed for prop "' + prop.name + '".' + ' Expected ' + expectedTypes.map(formatType).join(', ') + ', got ' + formatValue(value) + '.', vm); } return false; } var validator = options.validator; if (validator) { if (!validator(value)) { 'development' !== 'production' && warn('Invalid prop: custom validator check failed for prop "' + prop.name + '".', vm); return false; } } return true; } /** * Force parsing value with coerce option. * * @param {*} value * @param {Object} options * @return {*} */ function coerceProp(prop, value, vm) { var coerce = prop.options.coerce; if (!coerce) { return value; } if (typeof coerce === 'function') { return coerce(value); } else { 'development' !== 'production' && warn('Invalid coerce for prop "' + prop.name + '": expected function, got ' + typeof coerce + '.', vm); return value; } } /** * Assert the type of a value * * @param {*} value * @param {Function} type * @return {Object} */ function assertType(value, type) { var valid; var expectedType; if (type === String) { expectedType = 'string'; valid = typeof value === expectedType; } else if (type === Number) { expectedType = 'number'; valid = typeof value === expectedType; } else if (type === Boolean) { expectedType = 'boolean'; valid = typeof value === expectedType; } else if (type === Function) { expectedType = 'function'; valid = typeof value === expectedType; } else if (type === Object) { expectedType = 'object'; valid = isPlainObject(value); } else if (type === Array) { expectedType = 'array'; valid = isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType }; } /** * Format type for output * * @param {String} type * @return {String} */ function formatType(type) { return type ? type.charAt(0).toUpperCase() + type.slice(1) : 'custom type'; } /** * Format value * * @param {*} value * @return {String} */ function formatValue(val) { return Object.prototype.toString.call(val).slice(8, -1); } 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) { updateProp(child, prop, 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 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 = 'transition'; var TYPE_ANIMATION = 'animation'; var transDurationProp = transitionProp + 'Duration'; var animDurationProp = animationProp + 'Duration'; /** * If a just-entered element is applied the * leave class while its enter transition hasn't started yet, * and the transitioned property has the same value for both * enter/leave, then the leave transition will be skipped and * the transitionend event never fires. This function ensures * its callback to be called after a transition has started * by waiting for double raf. * * It falls back to setTimeout on devices that support CSS * transitions but not raf (e.g. Android 4.2 browser) - since * these environments are usually slow, we are giving it a * relatively large timeout. */ var raf = inBrowser && window.requestAnimationFrame; var waitForTransitionStart = raf /* istanbul ignore next */ ? function (fn) { raf(function () { raf(fn); }); } : function (fn) { setTimeout(fn, 50); }; /** * 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 = hooks && hooks.enterClass || id + '-enter'; this.leaveClass = hooks && hooks.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 = {}; // check css transition type this.type = hooks && hooks.type; /* istanbul ignore if */ if ('development' !== 'production') { if (this.type && this.type !== TYPE_TRANSITION && this.type !== TYPE_ANIMATION) { warn('invalid CSS transition type for transition="' + this.id + '": ' + this.type, vm); } } // bind var self = this;['enterNextTick', 'enterDone', 'leaveNextTick', 'leaveDone'].forEach(function (m) { self[m] = bind(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 () { var _this = this; // prevent transition skipping this.justEntered = true; waitForTransitionStart(function () { _this.justEntered = false; }); 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.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(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) { if (/svg$/.test(el.namespaceURI)) { // SVG elements do not have offset(Width|Height) // so we need to check the client rect var rect = el.getBoundingClientRect(); return !(rect.width || rect.height); } else { return !(el.offsetWidth || el.offsetHeight || el.getClientRects().length); } } var transition$1 = { 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'; oldId = oldId || 'v'; el.__v_trans = new Transition(el, id, hooks, this.vm); removeClass(el, oldId + '-transition'); addClass(el, id + '-transition'); } }; var internalDirectives = { style: style, 'class': vClass, component: component, prop: propDef, transition: transition$1 }; // special binding prefixes var bindRE = /^v-bind:|^:/; var onRE = /^v-on:|^@/; var dirAttrRE = /^v-([^:]+)(?:$|:(.*)$)/; var modifierRE = /\.[^\.]+/g; var transitionRE = /^(v-bind:|:)?transition$/; // default directive priority var DEFAULT_PRIORITY = 1000; var DEFAULT_TERMINAL_PRIORITY = 2000; /** * 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) && !isScript(el) && 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) { /* istanbul ignore if */ if ('development' === 'production') {} 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) { function unlink(destroying) { teardownDirs(vm, dirs, destroying); if (context && contextDirs) { teardownDirs(context, contextDirs); } } // expose linked directives unlink.dirs = dirs; return unlink; } /** * 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 ('development' !== 'production' && !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, vm); 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 {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'); } } options._containerAttrs = options._replacerAttrs = null; 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 && !isScript(node)) { 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(); var attrs = hasAttrs && toArray(el.attributes); // check terminal directives (for & if) if (hasAttrs) { linkFn = checkTerminalDirectives(el, attrs, 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(attrs, 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: directives[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 = _toString(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; } 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 {Array} attrs * @param {Object} options * @return {Function} terminalLinkFn */ function checkTerminalDirectives(el, attrs, 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 attr, name, value, modifiers, matched, dirName, rawName, arg, def, termDef; for (var i = 0, j = attrs.length; i < j; i++) { attr = attrs[i]; name = attr.name.replace(modifierRE, ''); if (matched = name.match(dirAttrRE)) { def = resolveAsset(options, 'directives', matched[1]); if (def && def.terminal) { if (!termDef || (def.priority || DEFAULT_TERMINAL_PRIORITY) > termDef.priority) { termDef = def; rawName = attr.name; modifiers = parseModifiers(attr.name); value = attr.value; dirName = matched[1]; arg = matched[2]; } } } } if (termDef) { return makeTerminalNodeLinkFn(el, dirName, value, options, termDef, rawName, arg, modifiers); } } 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 * @param {String} [rawName] * @param {String} [arg] * @param {Object} [modifiers] * @return {Function} terminalLinkFn */ function makeTerminalNodeLinkFn(el, dirName, value, options, def, rawName, arg, modifiers) { var parsed = parseDirective(value); var descriptor = { name: dirName, arg: arg, expression: parsed.expression, filters: parsed.filters, raw: value, attr: rawName, modifiers: modifiers, def: def }; // 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, matched; 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', directives.bind, tokens); // 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.', options); } } } 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', directives.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', directives.bind); } } else // normal directives if (matched = name.match(dirAttrRE)) { dirName = matched[1]; arg = matched[2]; // skip v-else (when used with v-show) if (dirName === 'else') { continue; } dirDef = resolveAsset(options, 'directives', dirName, true); if (dirDef) { pushDir(dirName, dirDef); } } } /** * Push a directive. * * @param {String} dirName * @param {Object|Function} def * @param {Array} [interpTokens] */ function pushDir(dirName, def, interpTokens) { var hasOneTimeToken = interpTokens && hasOneTime(interpTokens); var parsed = !hasOneTimeToken && parseDirective(value); dirs.push({ name: dirName, attr: rawName, raw: rawValue, def: def, arg: arg, modifiers: modifiers, // conversion from interpolation strings with one-time token // to expression is differed until directive bind time so that we // have access to the actual vm context for one-time bindings. expression: parsed && parsed.expression, filters: parsed && parsed.filters, interp: interpTokens, hasOneTime: hasOneTimeToken }); } 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); } }; } /** * Check if an interpolation string contains one-time tokens. * * @param {Array} tokens * @return {Boolean} */ function hasOneTime(tokens) { var i = tokens.length; while (i--) { if (tokens[i].oneTime) return true; } } function isScript(el) { return el.tagName === 'SCRIPT' && (!el.hasAttribute('type') || el.getAttribute('type') === 'text/javascript'); } 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 (isFragment(el)) { // 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' && !parseText(value) && (value = value.trim())) { value.split(/\s+/).forEach(function (cls) { addClass(to, cls); }); } } } /** * Scan and determine slot content distribution. * We do this during transclusion instead at compile time so that * the distribution is decoupled from the compilation order of * the slots. * * @param {Element|DocumentFragment} template * @param {Element} content * @param {Vue} vm */ function resolveSlots(vm, content) { if (!content) { return; } var contents = vm._slotContents = Object.create(null); var el, name; for (var i = 0, l = content.children.length; i < l; i++) { el = content.children[i]; /* eslint-disable no-cond-assign */ if (name = el.getAttribute('slot')) { (contents[name] || (contents[name] = [])).push(el); } /* eslint-enable no-cond-assign */ if ('development' !== 'production' && getBindAttr(el, 'slot')) { warn('The "slot" attribute must be static.', vm.$parent); } } for (name in contents) { contents[name] = extractFragment(contents[name], content); } if (content.hasChildNodes()) { var nodes = content.childNodes; if (nodes.length === 1 && nodes[0].nodeType === 3 && !nodes[0].data.trim()) { return; } contents['default'] = extractFragment(content.childNodes, content); } } /** * Extract qualified content nodes from a node list. * * @param {NodeList} nodes * @return {DocumentFragment} */ function extractFragment(nodes, parent) { var frag = document.createDocumentFragment(); nodes = toArray(nodes); for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; if (isTemplate(node) && !node.hasAttribute('v-if') && !node.hasAttribute('v-for')) { parent.removeChild(node); node = parseTemplate(node, true); } frag.appendChild(node); } return frag; } var compiler = Object.freeze({ compile: compile, compileAndLinkProps: compileAndLinkProps, compileRoot: compileRoot, transclude: transclude, resolveSlots: resolveSlots }); 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.', this); } // 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 dataFn = this.$options.data; var data = this._data = dataFn ? dataFn() : {}; if (!isPlainObject(data)) { data = {}; 'development' !== 'production' && warn('data functions should return an object.', this); } var props = this._props; // proxy data on instance var keys = Object.keys(data); var i, key; i = keys.length; while (i--) { key = keys[i]; // there are two scenarios where we can proxy a data key: // 1. it's not already defined as a prop // 2. it's provided via a instantiation option AND there are no // template prop present if (!props || !hasOwn(props, key)) { this._proxy(key); } else if ('development' !== 'production') { warn('Data field "' + key + '" is already defined ' + 'as a prop. To provide default value for a prop, use the "default" ' + 'prop option; if you want to pass prop values to an instantiation ' + 'call, use the "propsData" option.', this); } } // 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(userDef.get, this) : noop; def.set = userDef.set ? bind(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(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, value, handler; for (var i = 0, l = attrs.length; i < l; i++) { name = attrs[i].name; if (eventRE.test(name)) { name = name.replace(eventRE, ''); // force the expression into a statement so that // it always dynamically resolves the method to call (#2670) // kinda ugly hack, but does the job. value = attrs[i].value; if (isSimplePath(value)) { value += '.apply(this, $arguments)'; } handler = (vm._scope || vm._context).$eval(value, true); handler._fromParent = 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 + '".', vm); } } 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$1() {} /** * 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 {Object} descriptor * - {String} name * - {Object} def * - {String} expression * - {Array<Object>} [filters] * - {Object} [modifiers] * - {Boolean} literal * - {String} attr * - {String} arg * - {String} raw * - {String} [ref] * - {Array<Object>} [interp] * - {Boolean} [hasOneTime] * @param {Vue} vm * @param {Node} el * @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. */ 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$1; } var preProcess = this._preProcess ? bind(this._preProcess, this) : null; var postProcess = this._postProcess ? bind(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 = hyphenate(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 * @param {Boolean} [useCapture] */ Directive.prototype.on = function (event, handler, useCapture) { on(this.el, event, handler, useCapture);(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 */ 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); // resolve slot distribution resolveSlots(this, options._content); // 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'); }; /** * Initialize instance element. Called in the public * $mount() method. * * @param {Element} el */ Vue.prototype._initElement = function (el) { if (isFragment(el)) { 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 {Object} descriptor - parsed directive descriptor * @param {Node} node - target node * @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 && 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[write ? l - i - 1 : i]; fn = resolveAsset(this.$options, 'filters', filter.name, true); 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|Function} value * @param {Function} cb */ Vue.prototype._resolveComponent = function (value, cb) { var factory; if (typeof value === 'function') { factory = value; } else { factory = resolveAsset(this.$options, 'components', value, true); } /* istanbul ignore if */ 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.call(this, 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' + (typeof value === 'string' ? ': ' + value : '') + '. ' + (reason ? '\nReason: ' + reason : '')); }); } } else { // normal component cb(factory); } }; } var filterRE$1 = /[^|]\|[^|]/; 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) { var self = this; return function statementHandler() { self.$arguments = toArray(arguments); var result = res.get.call(self, self); self.$arguments = null; return result; }; } 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$1.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) { var key; for (key in this.$options.computed) { data[key] = clean(this[key]); } if (this._props) { for (key in this._props) { 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|Object} event * @return {Boolean} shouldPropagate */ Vue.prototype.$emit = function (event) { var isSource = typeof event === 'string'; event = isSource ? event : event.name; var cbs = this._events[event]; var shouldPropagate = isSource || !cbs; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; // this is a somewhat hacky solution to the question raised // in #2102: for an inline component listener like <comp @test="doThis">, // the propagation handling is somewhat broken. Therefore we // need to treat these inline callbacks differently. var hasParentCbs = isSource && cbs.some(function (cb) { return cb._fromParent; }); if (hasParentCbs) { shouldPropagate = false; } var args = toArray(arguments, 1); for (var i = 0, l = cbs.length; i < l; i++) { var cb = cbs[i]; var res = cb.apply(this, args); if (res === true && (!hasParentCbs || cb._fromParent)) { shouldPropagate = true; } } } return shouldPropagate; }; /** * Recursively broadcast an event to all children instances. * * @param {String|Object} event * @param {...*} additional arguments */ Vue.prototype.$broadcast = function (event) { var isSource = typeof event === 'string'; event = isSource ? event : event.name; // if no child has registered for this event, // then there's no need to broadcast. if (!this._eventsCount[event]) return; var children = this.$children; var args = toArray(arguments); if (isSource) { // use object event to indicate non-source emit // on children args[0] = { name: event, source: this }; } for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var shouldPropagate = child.$emit.apply(child, args); if (shouldPropagate) { child.$broadcast.apply(child, args); } } return this; }; /** * Recursively propagate an event up the parent chain. * * @param {String} event * @param {...*} additional arguments */ Vue.prototype.$dispatch = function (event) { var shouldPropagate = this.$emit.apply(this, arguments); if (!shouldPropagate) return; var parent = this.$parent; var args = toArray(arguments); // use object event to indicate non-source emit // on parents args[0] = { name: event, source: this }; while (parent) { shouldPropagate = parent.$emit.apply(parent, args); 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.', this); 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. * * @param {Boolean} remove * @param {Boolean} deferCleanup */ 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] * @param {Object} [scope] * @param {Fragment} [frag] * @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 instance APIs dataAPI(Vue); domAPI(Vue); eventsAPI(Vue); lifecycleAPI(Vue); var slot = { priority: SLOT, params: ['name'], bind: function bind() { // this was resolved during component transclusion var name = this.params.name || 'default'; var content = this.vm._slotContents && this.vm._slotContents[name]; if (!content || !content.hasChildNodes()) { this.fallback(); } else { this.compile(content.cloneNode(true), this.vm._context, this.vm); } }, compile: function compile(content, context, host) { if (content && context) { if (this.el.hasChildNodes() && content.childNodes.length === 1 && content.childNodes[0].nodeType === 1 && content.childNodes[0].hasAttribute('v-if')) { // if the inserted slot has v-if // inject fallback content as the v-else var elseBlock = document.createElement('template'); elseBlock.setAttribute('v-else', ''); elseBlock.innerHTML = this.el.innerHTML; // the else block should be compiled in child scope elseBlock._context = this.vm; content.appendChild(elseBlock); } 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 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, true); if (partial) { this.factory = new FragmentFactory(this.vm, partial); vIf.insert.call(this); } }, unbind: function unbind() { if (this.frag) { this.frag.destroy(); } } }; var elementDirectives = { slot: slot, partial: partial }; 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; n = toNumber(n); 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 = Array.prototype.concat.apply([], toArray(arguments, n)); 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|Array<String>|Function} ...sortKeys * @param {Number} [order] */ function orderBy(arr) { var comparator = null; var sortKeys = undefined; arr = convertArray(arr); // determine order (last argument) var args = toArray(arguments, 1); var order = args[args.length - 1]; if (typeof order === 'number') { order = order < 0 ? -1 : 1; args = args.length > 1 ? args.slice(0, -1) : args; } else { order = 1; } // determine sortKeys & comparator var firstArg = args[0]; if (!firstArg) { return arr; } else if (typeof firstArg === 'function') { // custom comparator comparator = function (a, b) { return firstArg(a, b) * order; }; } else { // string keys. flatten first sortKeys = Array.prototype.concat.apply([], args); comparator = function (a, b, i) { i = i || 0; return i >= sortKeys.length - 1 ? baseCompare(a, b, i) : baseCompare(a, b, i) || comparator(a, b, i + 1); }; } function baseCompare(a, b, sortKeyIndex) { var sortKey = sortKeys[sortKeyIndex]; if (sortKey) { 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; } // sort on a copy to avoid mutating original array return arr.slice().sort(comparator); } /** * 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, arguments.length > 1 ? 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 * @param {Number} decimals Decimal places */ currency: function currency(value, _currency, decimals) { value = parseFloat(value); if (!isFinite(value) || !value && value !== 0) return ''; _currency = _currency != null ? _currency : '$'; decimals = decimals != null ? decimals : 2; var stringified = Math.abs(value).toFixed(decimals); var _int = decimals ? stringified.slice(0, -1 - decimals) : stringified; var i = _int.length % 3; var head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? ',' : '') : ''; var _float = decimals ? stringified.slice(-1 - decimals) : ''; var sign = value < 0 ? '-' : ''; return sign + _currency + 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); var length = args.length; if (length > 1) { var index = value % 10 - 1; return index in args ? args[index] : args[length - 1]; } else { return 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); } }; function installGlobalAPI (Vue) { /** * 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: directives, elementDirectives: elementDirectives, filters: filters, transitions: {}, components: {}, partials: {}, replace: true }; /** * 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, 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 + '". Component names ' + 'can only contain alphanumeric characaters and the hyphen.'); name = null; } } var Sub = createClass(name || 'VueComponent'); 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; }; /** * A function that returns a sub-class constructor with the * given name. This gives us much nicer output when * logging instances in the console. * * @param {String} name * @return {Function} */ function createClass(name) { /* eslint-disable no-new-func */ return new Function('return function ' + classify(name) + ' (options) { this._init(options) }')(); /* eslint-enable no-new-func */ } /** * 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)) { if (!definition.name) { definition.name = id; } definition = Vue.extend(definition); } this.options[type + 's'][id] = definition; return definition; } }; }); // expose internal transition API extend(Vue.transition, transition); } installGlobalAPI(Vue); Vue.version = '1.0.26'; // devtools global hook /* istanbul ignore next */ setTimeout(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue); } else if ('development' !== 'production' && inBrowser && /Chrome\/\d+/.test(window.navigator.userAgent)) { console.log('Download the Vue Devtools for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools'); } } }, 0); return Vue; }));
src/shared/title.js
bschneier/credit-cards-front-end
import React from 'react'; import { Row } from 'react-bootstrap'; export default class Title extends React.Component { render() { return ( <Row bsClass="row credit-cards-title">Credit Card Rewards</Row> ); } }
app/components/main.js
gap91/byu-ride-board
var React = require("react"); var ReactDOM = require('react-dom'); var ReactRouter = require("react-router"); var Router = ReactRouter.Router; var Route = ReactRouter.Route; var IndexRoute = ReactRouter.IndexRoute; var New = require("./ride_board.js"); var Home = require("./home.js"); var Login = require("./login.js"); var Register = require("./register.js"); var Dashboard = require("./dashboard.js"); var Create = require("./create.js"); var Search = require("./search_entry.js"); require("../../node_modules/bootstrap/dist/css/bootstrap.min.css"); require("../css/app.css"); var routes = ( <Router> <Route name="new" path="/" component ={New}> <IndexRoute component = {Home} /> <Route name ="dashboard" path="/dashboard" component={Dashboard} /> <Route name ="create" path="/create" component={Create} /> <Route name ="search" path="/search" component={Search} /> <Route name ="register" path="/register" component={Register} /> <Route name ="login" path="/login" component={Login} /> </Route> </Router> ); ReactDOM.render(routes, document.getElementById('content'));
src/frontend/components/notfound.js
PiTeam/garage-pi
import React from 'react'; export const PageNotFound = () => ( <h1>{'Page not Found '}</h1> );
docs/app/Examples/collections/Table/Variations/TableExampleLarge.js
shengnian/shengnian-ui-react
import React from 'react' import { Table } from 'shengnian-ui-react' const TableExampleLarge = () => ( <Table size='large'> <Table.Header> <Table.Row> <Table.HeaderCell>Name</Table.HeaderCell> <Table.HeaderCell>Status</Table.HeaderCell> <Table.HeaderCell>Notes</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell>John</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>Requires call</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jill</Table.Cell> <Table.Cell>Denied</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> </Table.Body> <Table.Footer> <Table.Row> <Table.HeaderCell>3 People</Table.HeaderCell> <Table.HeaderCell>2 Approved</Table.HeaderCell> <Table.HeaderCell /> </Table.Row> </Table.Footer> </Table> ) export default TableExampleLarge
app/components/DragAndDropComponents/ElementDragPreview.js
voyagr/voyagr
import React, { Component } from 'react'; import whatTypeElementToRender from '../utils/whatTypeElementToRender' const styles = { display: 'inline-block', boxShadow: '10px 10px 5px #888888', }; export default class ElementDragPreview extends Component { render() { return ( <div style={styles}> {whatTypeElementToRender(this.props)} </div> ); } }
components/frontend/src/measurement/MeasurementSources.js
ICTU/quality-time
import React from 'react'; import { SourceStatus } from './SourceStatus'; export function MeasurementSources({ metric }) { const sources = metric.latest_measurement?.sources ?? []; return sources.map( (source, index) => [index > 0 && ", ", <SourceStatus key={source.source_uuid} metric={metric} measurement_source={source} />] ); }
src/components/svg/ChevronSvg.js
contor-cloud/contor-cloud.github.io
import React from 'react' const ChevronSvg = ({size = 10, cssProps = {}}: { size: number, cssProps: Object, }) => ( <svg x="0px" y="0px" viewBox="0 0 926.23699 573.74994" width={size} height={size} css={cssProps} version="1.1"> <g transform="translate(904.92214,-879.1482)"> <path d={` m -673.67664,1221.6502 -231.2455,-231.24803 55.6165, -55.627 c 30.5891,-30.59485 56.1806,-55.627 56.8701,-55.627 0.6894, 0 79.8637,78.60862 175.9427,174.68583 l 174.6892,174.6858 174.6892, -174.6858 c 96.079,-96.07721 175.253196,-174.68583 175.942696, -174.68583 0.6895,0 26.281,25.03215 56.8701, 55.627 l 55.6165,55.627 -231.245496,231.24803 c -127.185,127.1864 -231.5279,231.248 -231.873,231.248 -0.3451,0 -104.688, -104.0616 -231.873,-231.248 z `} fill="currentColor" /> </g> </svg> ) export default ChevronSvg
files/rxjs/2.3.2/rx.all.js
petkaantonov/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }; // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { /** * @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); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return Observable; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); return function () { if (promise && promise.abort) { promise.abort(); } } }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new Error('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throw(new Error('Error')); * var res = Rx.Observable.throw(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.do(observer); * var res = observable.do(onNext); * var res = observable.do(onNext, onError); * var res = observable.do(onNext, onError, onCompleted); * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (!onError) { observer.onError(err); } else { try { onError(err); } catch (e) { observer.onError(e); } observer.onError(err); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * * @example * var res = source.takeLast(5); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } return typeof selector === 'function' ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; observableProto.concatMapObserver = function(onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); }); }).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { observer.onError(e); return; } } hashSet.push(key) && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var map = new Dictionary(), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key, i, len, items; try { key = keySelector(x); } catch (e) { items = map.getValues(); for (i = 0, len = items.length; i < len; i++) { items[i].onError(e); } observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { items = map.getValues(); for (i = 0, len = items.length; i < len; i++) { items[i].onError(e); } observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { items = map.getValues(); for (i = 0, len = items.length; i < len; i++) { items[i].onError(exn); } observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { items = map.getValues(); for (i = 0, len = items.length; i < len; i++) { items[i].onError(e); } observer.onError(e); return; } writer.onNext(element); }, function (ex) { var items = map.getValues(); for(var i = 0, len = items.length; i < len; i++) { items[i].onError(ex); } observer.onError(ex); }, function () { var items = map.getValues(); for(var i = 0, len = items.length; i < len; i++) { items[i].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }, thisArg); } return typeof selector === 'function' ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); }); }).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (observer) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { observer.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { observer.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, observer.onError.bind(observer), function () { observer.onNext(list); observer.onCompleted(); }); }); } function firstOnly(x) { if (x.length === 0) { throw new Error(sequenceContainsNoElements); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.aggregate(function (acc, x) { return acc + x; }); * 2 - res = source.aggregate(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.aggregate = function () { var seed, hasSeed, accumulator; if (arguments.length === 2) { seed = arguments[0]; hasSeed = true; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.reduce(function (acc, x) { return acc + x; }); * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0); * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var seed, hasSeed; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @example * var result = source.any(); * var result = source.any(function (x) { return x > 3; }); * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = observableProto.any = function (predicate, thisArg) { var source = this; return predicate ? source.where(predicate, thisArg).any() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }); }; /** * Determines whether an observable sequence is empty. * * @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, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * * @example * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); * * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }; }; function createListener (element, name, handler) { // 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 (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; } // 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.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, _super); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { _super.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (_super) { function RemovableDisposable (subject, observer) { this.subject = subject; this.observer = observer; }; RemovableDisposable.prototype.dispose = function () { this.observer.dispose(); if (!this.subject.isDisposed) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); } }; function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = new RemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, _super); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; _super.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /* @private */ _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { var observer; checkDisposed.call(this); if (!this.isStopped) { var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onNext(value); observer.ensureActive(); } } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; } }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, subject.subscribe.bind(subject)); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if (candidate & 1 === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash<<5)-hash)+character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof obj === 'string') { return stringHashFn(valueOf); } } if (obj.getHashCode) { return obj.getHashCode(); } var id = 17 * uniqueIdCounter++; obj.getHashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new Error('out of range'); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { return this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), 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 () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = argsOrArray(arguments, 0); return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeObservable().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwException(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = (function () { /** * @constructor * @private */ function Map() { this.keys = []; this.values = []; } /** * @private * @memberOf Map# */ Map.prototype['delete'] = function (key) { var i = this.keys.indexOf(key); if (i !== -1) { this.keys.splice(i, 1); this.values.splice(i, 1); } return i !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.get = function (key, fallback) { var i = this.keys.indexOf(key); return i !== -1 ? this.values[i] : fallback; }; /** * @private * @memberOf Map# */ Map.prototype.set = function (key, value) { var i = this.keys.indexOf(key); if (i !== -1) { this.values[i] = value; } this.values[this.keys.push(key) - 1] = value; }; /** * @private * @memberOf Map# */ Map.prototype.size = function () { return this.keys.length; }; /** * @private * @memberOf Map# */ Map.prototype.has = function (key) { return this.keys.indexOf(key) !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.getKeys = function () { return this.keys.slice(0); }; /** * @private * @memberOf Map# */ Map.prototype.getValues = function () { return this.values.slice(0); }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * * @param other Observable sequence to match in addition to the current pattern. * @return Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { var patterns = this.patterns.slice(0); patterns.push(other); return new Pattern(patterns); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.thenDo = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } // Active Plan function ActivePlan(joinObserverArray, onNext, onCompleted) { var i, joinObserver; this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (i = 0; i < this.joinObserverArray.length; i++) { joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { var values = this.joinObservers.getValues(); for (var i = 0, len = values.length; i < len; i++) { values[i].queue.shift(); } }; ActivePlan.prototype.match = function () { var firstValues, i, len, isCompleted, values, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { firstValues = []; isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); if (this.joinObserverArray[i].queue[0].kind === 'C') { isCompleted = true; } } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); values = []; for (i = 0; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; /** @private */ var JoinObserver = (function (_super) { inherits(JoinObserver, _super); /** * @constructor * @private */ function JoinObserver(source, onError) { _super.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { this.onError(notification.exception); return; } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.error = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.completed = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.removeActivePlan = function (activePlan) { var idx = this.activePlans.indexOf(activePlan); this.activePlans.splice(idx, 1); if (this.activePlans.length === 0) { this.dispose(); } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var plans = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var activePlans = [], externalSubscriptions = new Map(), group, i, len, joinObserver, joinValues, outObserver; outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { var values = externalSubscriptions.getValues(); for (var j = 0, jlen = values.length; j < jlen; j++) { values[j].onError(exception); } observer.onError(exception); }, observer.onCompleted.bind(observer)); try { for (i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); if (activePlans.length === 0) { outObserver.onCompleted(); } })); } } catch (e) { observableThrow(e).subscribe(observer); } group = new CompositeDisposable(); joinValues = externalSubscriptions.getValues(); for (i = 0, len = joinValues.length; i < len; i++) { joinObserver = joinValues[i]; joinObserver.subscribe(); group.add(joinObserver); } return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { 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) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * * @example * 1 - res = Rx.Observable.timer(new Date()); * 2 - res = Rx.Observable.timer(new Date(), 1000); * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); * * 5 - res = Rx.Observable.timer(5000); * 6 - res = Rx.Observable.timer(5000, 1000); * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * * @example * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (typeof timeShiftOrScheduler === 'object') { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe(function (x) { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; isSpan && (nextSpan += timeShift); isShift && (nextShift += timeShift); m.setDisposable(scheduler.scheduleWithRelative(ts, function () { var s; if (isShift) { s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } if (isSpan) { s = q.shift(); s.onCompleted(); } createTimer(); })); } }); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @example * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items * * @memberOf Observable# * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var createTimer, groupDisposable, n = 0, refCountDisposable, s = new Subject() timerD = new SerialDisposable(), windowId = 0; groupDisposable = new CompositeDisposable(timerD); refCountDisposable = new RefCountDisposable(groupDisposable); observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe(function (x) { var newId = 0, newWindow = false; s.onNext(x); n++; if (n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); })); return refCountDisposable; function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { var newId; if (id !== windowId) { return; } n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * * @example * 1 - res = source.timeout(new Date()); // As a date * 2 - res = source.timeout(5000); // 5 seconds * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { other || (other = observableThrow(new Error('Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); var createTimer = function () { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); }; createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(function () { start(); }, observer.onError.bind(observer), function () { start(); })); } return new CompositeDisposable(subscription, delays); }); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * * @example * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); * * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; var firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false, setTimer = function (timeout) { var myId = id, timerWins = function () { return id === myId; }; var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } d.dispose(); }, function (e) { if (timerWins()) { observer.onError(e); } }, function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } })); }; setTimer(firstTimeout); var observerWins = function () { var res = !switched; if (res) { id++; } return res; }; original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(timeout); } }, function (e) { if (observerWins()) { observer.onError(e); } }, function () { if (observerWins()) { observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); * * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The throttled sequence. */ observableProto.throttleWithSelector = function (throttleDurationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(x); } catch (e) { observer.onError(e); return; } hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); if (hasValue) { observer.onNext(value); } observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } observer.onCompleted(); }); }); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * * @example * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { observer.onNext(next.value); } } observer.onCompleted(); }); }); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { res.push(next.value); } } observer.onNext(res); observer.onCompleted(); }); }); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer)); }); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler.scheduleWithRelative(duration, function () { open = true; }), source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * * @example * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} scheduler Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { observer.onCompleted(); }), source.subscribe(observer)); }); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this; return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selector.call(thisArg, x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (_super) { function notImplemented() { throw new Error('Not implemented'); } function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, _super); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { 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 (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
src/components/Clock.js
matheuscorreia/podomoro
import React from 'react'; import { Circle } from 'rc-progress'; import {formatTimer} from '../helpers/'; import '../main.css'; export default class Clock extends React.Component { render(){ let label = formatTimer(this.props.secondsLeft); let percentage = this.props.secondsLeft / this.props.secondsOnStart * 100; return ( <div className="clock-container center-align"> <div className="timer center-align"> <h2>{label}</h2> </div> <a className="waves-effect waves-light btn-floating btn-large red startBtn" onClick={() => { this.props.onStartClick() }}> <i className="material-icons">{this.props.isRunning ? "pause" : "play_arrow"}</i> </a> <Circle percent={percentage} strokeWidth="2" strokeColor="#C4C9E8" /> </div> ); } }
examples/optimistic-updates.js
lelandrichardson/react-flux-store-mixin
// Actions.js // ========== var Flux = require('react-flux'); var $http = require('$http'); var Constants = Flux.createConstants([ "LIKE", "UNLIKE" ], "ACTIONS"); var Actions = Flux.createActions({ like: [Constants.LIKE, function ( entityId ) { return $http.post(`/entity/${entityId}/like`); }], unlike: [Constants.UNLIKE, function ( entityId ) { return $http.post(`/entity/${entityId}/unlike`); }] }); module.exports = Actions; module.exports.Constants = Constants; // EntityStore.js // ============== var Flux = require('react-flux'); var Constants = require('../actions/Actions').Constants; var OptimisticStoreMixin = require('../mixins/OptimisticStoreMixin'); var EntityStore = Flux.createStore({ mixins: [OptimisticStoreMixin] }, [ // OPTIMISTIC! // NOTE: // at the moment, with the react-flux framework, it is really difficult // to get the entityId to be passed into this function. [Constants.LIKE, function ( entityId ) { this.optimisticUpdate(entityId, `LIKE_UNLIKE_${entityId}`, { liked: true }); }], [Constants.UNLIKE, function ( entityId ) { this.optimisticUpdate(entityId, `LIKE_UNLIKE_${entityId}`, { liked: false }); }], // SUCCESS! [Constants.LIKE_SUCCESS, function ( entity ) { this.undoOptimisticUpdate(entity.id, `LIKE_UNLIKE_${entity.id}`); this.addOrUpdateEntity(entity); }], [Constants.UNLIKE_SUCCESS, function ( entity ) { this.undoOptimisticUpdate(entity.id, `LIKE_UNLIKE_${entity.id}`); this.addOrUpdateEntity(entity); }], // FAILURE! [Constants.UNLIKE_FAIL, function ( entityId ) { this.undoOptimisticUpdate(entityId, `LIKE_UNLIKE_${entityId}`); }], [Constants.UNLIKE_FAIL, function ( entityId ) { this.undoOptimisticUpdate(entityId, `LIKE_UNLIKE_${entityId}`); }] ]); module.exports = EntityStore;
lib/yuilib/2in3/2.9.0/build/yui2-container/yui2-container-debug.js
merrill-oakland/moodle
YUI.add('yui2-containercore', function(Y) { Y.use('yui2-container'); }, '3.3.0' ,{"requires": ["yui2-yahoo", "yui2-dom", "yui2-event"]}); YUI.add('yui2-container', function(Y) { var YAHOO = Y.YUI2; /* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ (function () { /** * Config is a utility used within an Object to allow the implementer to * maintain a list of local configuration properties and listen for changes * to those properties dynamically using CustomEvent. The initial values are * also maintained so that the configuration can be reset at any given point * to its initial state. * @namespace YAHOO.util * @class Config * @constructor * @param {Object} owner The owner Object to which this Config Object belongs */ YAHOO.util.Config = function (owner) { if (owner) { this.init(owner); } if (!owner) { YAHOO.log("No owner specified for Config object", "error", "Config"); } }; var Lang = YAHOO.lang, CustomEvent = YAHOO.util.CustomEvent, Config = YAHOO.util.Config; /** * Constant representing the CustomEvent type for the config changed event. * @property YAHOO.util.Config.CONFIG_CHANGED_EVENT * @private * @static * @final */ Config.CONFIG_CHANGED_EVENT = "configChanged"; /** * Constant representing the boolean type string * @property YAHOO.util.Config.BOOLEAN_TYPE * @private * @static * @final */ Config.BOOLEAN_TYPE = "boolean"; Config.prototype = { /** * Object reference to the owner of this Config Object * @property owner * @type Object */ owner: null, /** * Boolean flag that specifies whether a queue is currently * being executed * @property queueInProgress * @type Boolean */ queueInProgress: false, /** * Maintains the local collection of configuration property objects and * their specified values * @property config * @private * @type Object */ config: null, /** * Maintains the local collection of configuration property objects as * they were initially applied. * This object is used when resetting a property. * @property initialConfig * @private * @type Object */ initialConfig: null, /** * Maintains the local, normalized CustomEvent queue * @property eventQueue * @private * @type Object */ eventQueue: null, /** * Custom Event, notifying subscribers when Config properties are set * (setProperty is called without the silent flag * @event configChangedEvent */ configChangedEvent: null, /** * Initializes the configuration Object and all of its local members. * @method init * @param {Object} owner The owner Object to which this Config * Object belongs */ init: function (owner) { this.owner = owner; this.configChangedEvent = this.createEvent(Config.CONFIG_CHANGED_EVENT); this.configChangedEvent.signature = CustomEvent.LIST; this.queueInProgress = false; this.config = {}; this.initialConfig = {}; this.eventQueue = []; }, /** * Validates that the value passed in is a Boolean. * @method checkBoolean * @param {Object} val The value to validate * @return {Boolean} true, if the value is valid */ checkBoolean: function (val) { return (typeof val == Config.BOOLEAN_TYPE); }, /** * Validates that the value passed in is a number. * @method checkNumber * @param {Object} val The value to validate * @return {Boolean} true, if the value is valid */ checkNumber: function (val) { return (!isNaN(val)); }, /** * Fires a configuration property event using the specified value. * @method fireEvent * @private * @param {String} key The configuration property's name * @param {value} Object The value of the correct type for the property */ fireEvent: function ( key, value ) { YAHOO.log("Firing Config event: " + key + "=" + value, "info", "Config"); var property = this.config[key]; if (property && property.event) { property.event.fire(value); } }, /** * Adds a property to the Config Object's private config hash. * @method addProperty * @param {String} key The configuration property's name * @param {Object} propertyObject The Object containing all of this * property's arguments */ addProperty: function ( key, propertyObject ) { key = key.toLowerCase(); YAHOO.log("Added property: " + key, "info", "Config"); this.config[key] = propertyObject; propertyObject.event = this.createEvent(key, { scope: this.owner }); propertyObject.event.signature = CustomEvent.LIST; propertyObject.key = key; if (propertyObject.handler) { propertyObject.event.subscribe(propertyObject.handler, this.owner); } this.setProperty(key, propertyObject.value, true); if (! propertyObject.suppressEvent) { this.queueProperty(key, propertyObject.value); } }, /** * Returns a key-value configuration map of the values currently set in * the Config Object. * @method getConfig * @return {Object} The current config, represented in a key-value map */ getConfig: function () { var cfg = {}, currCfg = this.config, prop, property; for (prop in currCfg) { if (Lang.hasOwnProperty(currCfg, prop)) { property = currCfg[prop]; if (property && property.event) { cfg[prop] = property.value; } } } return cfg; }, /** * Returns the value of specified property. * @method getProperty * @param {String} key The name of the property * @return {Object} The value of the specified property */ getProperty: function (key) { var property = this.config[key.toLowerCase()]; if (property && property.event) { return property.value; } else { return undefined; } }, /** * Resets the specified property's value to its initial value. * @method resetProperty * @param {String} key The name of the property * @return {Boolean} True is the property was reset, false if not */ resetProperty: function (key) { key = key.toLowerCase(); var property = this.config[key]; if (property && property.event) { if (key in this.initialConfig) { this.setProperty(key, this.initialConfig[key]); return true; } } else { return false; } }, /** * Sets the value of a property. If the silent property is passed as * true, the property's event will not be fired. * @method setProperty * @param {String} key The name of the property * @param {String} value The value to set the property to * @param {Boolean} silent Whether the value should be set silently, * without firing the property event. * @return {Boolean} True, if the set was successful, false if it failed. */ setProperty: function (key, value, silent) { var property; key = key.toLowerCase(); YAHOO.log("setProperty: " + key + "=" + value, "info", "Config"); if (this.queueInProgress && ! silent) { // Currently running through a queue... this.queueProperty(key,value); return true; } else { property = this.config[key]; if (property && property.event) { if (property.validator && !property.validator(value)) { return false; } else { property.value = value; if (! silent) { this.fireEvent(key, value); this.configChangedEvent.fire([key, value]); } return true; } } else { return false; } } }, /** * Sets the value of a property and queues its event to execute. If the * event is already scheduled to execute, it is * moved from its current position to the end of the queue. * @method queueProperty * @param {String} key The name of the property * @param {String} value The value to set the property to * @return {Boolean} true, if the set was successful, false if * it failed. */ queueProperty: function (key, value) { key = key.toLowerCase(); YAHOO.log("queueProperty: " + key + "=" + value, "info", "Config"); var property = this.config[key], foundDuplicate = false, iLen, queueItem, queueItemKey, queueItemValue, sLen, supercedesCheck, qLen, queueItemCheck, queueItemCheckKey, queueItemCheckValue, i, s, q; if (property && property.event) { if (!Lang.isUndefined(value) && property.validator && !property.validator(value)) { // validator return false; } else { if (!Lang.isUndefined(value)) { property.value = value; } else { value = property.value; } foundDuplicate = false; iLen = this.eventQueue.length; for (i = 0; i < iLen; i++) { queueItem = this.eventQueue[i]; if (queueItem) { queueItemKey = queueItem[0]; queueItemValue = queueItem[1]; if (queueItemKey == key) { /* found a dupe... push to end of queue, null current item, and break */ this.eventQueue[i] = null; this.eventQueue.push( [key, (!Lang.isUndefined(value) ? value : queueItemValue)]); foundDuplicate = true; break; } } } // this is a refire, or a new property in the queue if (! foundDuplicate && !Lang.isUndefined(value)) { this.eventQueue.push([key, value]); } } if (property.supercedes) { sLen = property.supercedes.length; for (s = 0; s < sLen; s++) { supercedesCheck = property.supercedes[s]; qLen = this.eventQueue.length; for (q = 0; q < qLen; q++) { queueItemCheck = this.eventQueue[q]; if (queueItemCheck) { queueItemCheckKey = queueItemCheck[0]; queueItemCheckValue = queueItemCheck[1]; if (queueItemCheckKey == supercedesCheck.toLowerCase() ) { this.eventQueue.push([queueItemCheckKey, queueItemCheckValue]); this.eventQueue[q] = null; break; } } } } } YAHOO.log("Config event queue: " + this.outputEventQueue(), "info", "Config"); return true; } else { return false; } }, /** * Fires the event for a property using the property's current value. * @method refireEvent * @param {String} key The name of the property */ refireEvent: function (key) { key = key.toLowerCase(); var property = this.config[key]; if (property && property.event && !Lang.isUndefined(property.value)) { if (this.queueInProgress) { this.queueProperty(key); } else { this.fireEvent(key, property.value); } } }, /** * Applies a key-value Object literal to the configuration, replacing * any existing values, and queueing the property events. * Although the values will be set, fireQueue() must be called for their * associated events to execute. * @method applyConfig * @param {Object} userConfig The configuration Object literal * @param {Boolean} init When set to true, the initialConfig will * be set to the userConfig passed in, so that calling a reset will * reset the properties to the passed values. */ applyConfig: function (userConfig, init) { var sKey, oConfig; if (init) { oConfig = {}; for (sKey in userConfig) { if (Lang.hasOwnProperty(userConfig, sKey)) { oConfig[sKey.toLowerCase()] = userConfig[sKey]; } } this.initialConfig = oConfig; } for (sKey in userConfig) { if (Lang.hasOwnProperty(userConfig, sKey)) { this.queueProperty(sKey, userConfig[sKey]); } } }, /** * Refires the events for all configuration properties using their * current values. * @method refresh */ refresh: function () { var prop; for (prop in this.config) { if (Lang.hasOwnProperty(this.config, prop)) { this.refireEvent(prop); } } }, /** * Fires the normalized list of queued property change events * @method fireQueue */ fireQueue: function () { var i, queueItem, key, value, property; this.queueInProgress = true; for (i = 0;i < this.eventQueue.length; i++) { queueItem = this.eventQueue[i]; if (queueItem) { key = queueItem[0]; value = queueItem[1]; property = this.config[key]; property.value = value; // Clear out queue entry, to avoid it being // re-added to the queue by any queueProperty/supercedes // calls which are invoked during fireEvent this.eventQueue[i] = null; this.fireEvent(key,value); } } this.queueInProgress = false; this.eventQueue = []; }, /** * Subscribes an external handler to the change event for any * given property. * @method subscribeToConfigEvent * @param {String} key The property name * @param {Function} handler The handler function to use subscribe to * the property's event * @param {Object} obj The Object to use for scoping the event handler * (see CustomEvent documentation) * @param {Boolean} overrideContext Optional. If true, will override * "this" within the handler to map to the scope Object passed into the * method. * @return {Boolean} True, if the subscription was successful, * otherwise false. */ subscribeToConfigEvent: function (key, handler, obj, overrideContext) { var property = this.config[key.toLowerCase()]; if (property && property.event) { if (!Config.alreadySubscribed(property.event, handler, obj)) { property.event.subscribe(handler, obj, overrideContext); } return true; } else { return false; } }, /** * Unsubscribes an external handler from the change event for any * given property. * @method unsubscribeFromConfigEvent * @param {String} key The property name * @param {Function} handler The handler function to use subscribe to * the property's event * @param {Object} obj The Object to use for scoping the event * handler (see CustomEvent documentation) * @return {Boolean} True, if the unsubscription was successful, * otherwise false. */ unsubscribeFromConfigEvent: function (key, handler, obj) { var property = this.config[key.toLowerCase()]; if (property && property.event) { return property.event.unsubscribe(handler, obj); } else { return false; } }, /** * Returns a string representation of the Config object * @method toString * @return {String} The Config object in string format. */ toString: function () { var output = "Config"; if (this.owner) { output += " [" + this.owner.toString() + "]"; } return output; }, /** * Returns a string representation of the Config object's current * CustomEvent queue * @method outputEventQueue * @return {String} The string list of CustomEvents currently queued * for execution */ outputEventQueue: function () { var output = "", queueItem, q, nQueue = this.eventQueue.length; for (q = 0; q < nQueue; q++) { queueItem = this.eventQueue[q]; if (queueItem) { output += queueItem[0] + "=" + queueItem[1] + ", "; } } return output; }, /** * Sets all properties to null, unsubscribes all listeners from each * property's change event and all listeners from the configChangedEvent. * @method destroy */ destroy: function () { var oConfig = this.config, sProperty, oProperty; for (sProperty in oConfig) { if (Lang.hasOwnProperty(oConfig, sProperty)) { oProperty = oConfig[sProperty]; oProperty.event.unsubscribeAll(); oProperty.event = null; } } this.configChangedEvent.unsubscribeAll(); this.configChangedEvent = null; this.owner = null; this.config = null; this.initialConfig = null; this.eventQueue = null; } }; /** * Checks to determine if a particular function/Object pair are already * subscribed to the specified CustomEvent * @method YAHOO.util.Config.alreadySubscribed * @static * @param {YAHOO.util.CustomEvent} evt The CustomEvent for which to check * the subscriptions * @param {Function} fn The function to look for in the subscribers list * @param {Object} obj The execution scope Object for the subscription * @return {Boolean} true, if the function/Object pair is already subscribed * to the CustomEvent passed in */ Config.alreadySubscribed = function (evt, fn, obj) { var nSubscribers = evt.subscribers.length, subsc, i; if (nSubscribers > 0) { i = nSubscribers - 1; do { subsc = evt.subscribers[i]; if (subsc && subsc.obj == obj && subsc.fn == fn) { return true; } } while (i--); } return false; }; YAHOO.lang.augmentProto(Config, YAHOO.util.EventProvider); }()); (function () { /** * The Container family of components is designed to enable developers to * create different kinds of content-containing modules on the web. Module * and Overlay are the most basic containers, and they can be used directly * or extended to build custom containers. Also part of the Container family * are four UI controls that extend Module and Overlay: Tooltip, Panel, * Dialog, and SimpleDialog. * @module container * @title Container * @requires yahoo, dom, event * @optional dragdrop, animation, button */ /** * Module is a JavaScript representation of the Standard Module Format. * Standard Module Format is a simple standard for markup containers where * child nodes representing the header, body, and footer of the content are * denoted using the CSS classes "hd", "bd", and "ft" respectively. * Module is the base class for all other classes in the YUI * Container package. * @namespace YAHOO.widget * @class Module * @constructor * @param {String} el The element ID representing the Module <em>OR</em> * @param {HTMLElement} el The element representing the Module * @param {Object} userConfig The configuration Object literal containing * the configuration that should be set for this module. See configuration * documentation for more details. */ YAHOO.widget.Module = function (el, userConfig) { if (el) { this.init(el, userConfig); } else { YAHOO.log("No element or element ID specified" + " for Module instantiation", "error"); } }; var Dom = YAHOO.util.Dom, Config = YAHOO.util.Config, Event = YAHOO.util.Event, CustomEvent = YAHOO.util.CustomEvent, Module = YAHOO.widget.Module, UA = YAHOO.env.ua, m_oModuleTemplate, m_oHeaderTemplate, m_oBodyTemplate, m_oFooterTemplate, /** * Constant representing the name of the Module's events * @property EVENT_TYPES * @private * @final * @type Object */ EVENT_TYPES = { "BEFORE_INIT": "beforeInit", "INIT": "init", "APPEND": "append", "BEFORE_RENDER": "beforeRender", "RENDER": "render", "CHANGE_HEADER": "changeHeader", "CHANGE_BODY": "changeBody", "CHANGE_FOOTER": "changeFooter", "CHANGE_CONTENT": "changeContent", "DESTROY": "destroy", "BEFORE_SHOW": "beforeShow", "SHOW": "show", "BEFORE_HIDE": "beforeHide", "HIDE": "hide" }, /** * Constant representing the Module's configuration properties * @property DEFAULT_CONFIG * @private * @final * @type Object */ DEFAULT_CONFIG = { "VISIBLE": { key: "visible", value: true, validator: YAHOO.lang.isBoolean }, "EFFECT": { key: "effect", suppressEvent: true, supercedes: ["visible"] }, "MONITOR_RESIZE": { key: "monitorresize", value: true }, "APPEND_TO_DOCUMENT_BODY": { key: "appendtodocumentbody", value: false } }; /** * Constant representing the prefix path to use for non-secure images * @property YAHOO.widget.Module.IMG_ROOT * @static * @final * @type String */ Module.IMG_ROOT = null; /** * Constant representing the prefix path to use for securely served images * @property YAHOO.widget.Module.IMG_ROOT_SSL * @static * @final * @type String */ Module.IMG_ROOT_SSL = null; /** * Constant for the default CSS class name that represents a Module * @property YAHOO.widget.Module.CSS_MODULE * @static * @final * @type String */ Module.CSS_MODULE = "yui-module"; /** * CSS classname representing the module header. NOTE: The classname is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @property YAHOO.widget.Module.CSS_HEADER * @static * @final * @type String */ Module.CSS_HEADER = "hd"; /** * CSS classname representing the module body. NOTE: The classname is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @property YAHOO.widget.Module.CSS_BODY * @static * @final * @type String */ Module.CSS_BODY = "bd"; /** * CSS classname representing the module footer. NOTE: The classname is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @property YAHOO.widget.Module.CSS_FOOTER * @static * @final * @type String */ Module.CSS_FOOTER = "ft"; /** * Constant representing the url for the "src" attribute of the iframe * used to monitor changes to the browser's base font size * @property YAHOO.widget.Module.RESIZE_MONITOR_SECURE_URL * @static * @final * @type String */ Module.RESIZE_MONITOR_SECURE_URL = "javascript:false;"; /** * Constant representing the buffer amount (in pixels) to use when positioning * the text resize monitor offscreen. The resize monitor is positioned * offscreen by an amount eqaul to its offsetHeight + the buffer value. * * @property YAHOO.widget.Module.RESIZE_MONITOR_BUFFER * @static * @type Number */ // Set to 1, to work around pixel offset in IE8, which increases when zoom is used Module.RESIZE_MONITOR_BUFFER = 1; /** * Singleton CustomEvent fired when the font size is changed in the browser. * Opera's "zoom" functionality currently does not support text * size detection. * @event YAHOO.widget.Module.textResizeEvent */ Module.textResizeEvent = new CustomEvent("textResize"); /** * Helper utility method, which forces a document level * redraw for Opera, which can help remove repaint * irregularities after applying DOM changes. * * @method YAHOO.widget.Module.forceDocumentRedraw * @static */ Module.forceDocumentRedraw = function() { var docEl = document.documentElement; if (docEl) { docEl.className += " "; docEl.className = YAHOO.lang.trim(docEl.className); } }; function createModuleTemplate() { if (!m_oModuleTemplate) { m_oModuleTemplate = document.createElement("div"); m_oModuleTemplate.innerHTML = ("<div class=\"" + Module.CSS_HEADER + "\"></div>" + "<div class=\"" + Module.CSS_BODY + "\"></div><div class=\"" + Module.CSS_FOOTER + "\"></div>"); m_oHeaderTemplate = m_oModuleTemplate.firstChild; m_oBodyTemplate = m_oHeaderTemplate.nextSibling; m_oFooterTemplate = m_oBodyTemplate.nextSibling; } return m_oModuleTemplate; } function createHeader() { if (!m_oHeaderTemplate) { createModuleTemplate(); } return (m_oHeaderTemplate.cloneNode(false)); } function createBody() { if (!m_oBodyTemplate) { createModuleTemplate(); } return (m_oBodyTemplate.cloneNode(false)); } function createFooter() { if (!m_oFooterTemplate) { createModuleTemplate(); } return (m_oFooterTemplate.cloneNode(false)); } Module.prototype = { /** * The class's constructor function * @property contructor * @type Function */ constructor: Module, /** * The main module element that contains the header, body, and footer * @property element * @type HTMLElement */ element: null, /** * The header element, denoted with CSS class "hd" * @property header * @type HTMLElement */ header: null, /** * The body element, denoted with CSS class "bd" * @property body * @type HTMLElement */ body: null, /** * The footer element, denoted with CSS class "ft" * @property footer * @type HTMLElement */ footer: null, /** * The id of the element * @property id * @type String */ id: null, /** * A string representing the root path for all images created by * a Module instance. * @deprecated It is recommend that any images for a Module be applied * via CSS using the "background-image" property. * @property imageRoot * @type String */ imageRoot: Module.IMG_ROOT, /** * Initializes the custom events for Module which are fired * automatically at appropriate times by the Module class. * @method initEvents */ initEvents: function () { var SIGNATURE = CustomEvent.LIST; /** * CustomEvent fired prior to class initalization. * @event beforeInitEvent * @param {class} classRef class reference of the initializing * class, such as this.beforeInitEvent.fire(Module) */ this.beforeInitEvent = this.createEvent(EVENT_TYPES.BEFORE_INIT); this.beforeInitEvent.signature = SIGNATURE; /** * CustomEvent fired after class initalization. * @event initEvent * @param {class} classRef class reference of the initializing * class, such as this.beforeInitEvent.fire(Module) */ this.initEvent = this.createEvent(EVENT_TYPES.INIT); this.initEvent.signature = SIGNATURE; /** * CustomEvent fired when the Module is appended to the DOM * @event appendEvent */ this.appendEvent = this.createEvent(EVENT_TYPES.APPEND); this.appendEvent.signature = SIGNATURE; /** * CustomEvent fired before the Module is rendered * @event beforeRenderEvent */ this.beforeRenderEvent = this.createEvent(EVENT_TYPES.BEFORE_RENDER); this.beforeRenderEvent.signature = SIGNATURE; /** * CustomEvent fired after the Module is rendered * @event renderEvent */ this.renderEvent = this.createEvent(EVENT_TYPES.RENDER); this.renderEvent.signature = SIGNATURE; /** * CustomEvent fired when the header content of the Module * is modified * @event changeHeaderEvent * @param {String/HTMLElement} content String/element representing * the new header content */ this.changeHeaderEvent = this.createEvent(EVENT_TYPES.CHANGE_HEADER); this.changeHeaderEvent.signature = SIGNATURE; /** * CustomEvent fired when the body content of the Module is modified * @event changeBodyEvent * @param {String/HTMLElement} content String/element representing * the new body content */ this.changeBodyEvent = this.createEvent(EVENT_TYPES.CHANGE_BODY); this.changeBodyEvent.signature = SIGNATURE; /** * CustomEvent fired when the footer content of the Module * is modified * @event changeFooterEvent * @param {String/HTMLElement} content String/element representing * the new footer content */ this.changeFooterEvent = this.createEvent(EVENT_TYPES.CHANGE_FOOTER); this.changeFooterEvent.signature = SIGNATURE; /** * CustomEvent fired when the content of the Module is modified * @event changeContentEvent */ this.changeContentEvent = this.createEvent(EVENT_TYPES.CHANGE_CONTENT); this.changeContentEvent.signature = SIGNATURE; /** * CustomEvent fired when the Module is destroyed * @event destroyEvent */ this.destroyEvent = this.createEvent(EVENT_TYPES.DESTROY); this.destroyEvent.signature = SIGNATURE; /** * CustomEvent fired before the Module is shown * @event beforeShowEvent */ this.beforeShowEvent = this.createEvent(EVENT_TYPES.BEFORE_SHOW); this.beforeShowEvent.signature = SIGNATURE; /** * CustomEvent fired after the Module is shown * @event showEvent */ this.showEvent = this.createEvent(EVENT_TYPES.SHOW); this.showEvent.signature = SIGNATURE; /** * CustomEvent fired before the Module is hidden * @event beforeHideEvent */ this.beforeHideEvent = this.createEvent(EVENT_TYPES.BEFORE_HIDE); this.beforeHideEvent.signature = SIGNATURE; /** * CustomEvent fired after the Module is hidden * @event hideEvent */ this.hideEvent = this.createEvent(EVENT_TYPES.HIDE); this.hideEvent.signature = SIGNATURE; }, /** * String identifying whether the current platform is windows or mac. This property * currently only identifies these 2 platforms, and returns false otherwise. * @property platform * @deprecated Use YAHOO.env.ua * @type {String|Boolean} */ platform: function () { var ua = navigator.userAgent.toLowerCase(); if (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1) { return "windows"; } else if (ua.indexOf("macintosh") != -1) { return "mac"; } else { return false; } }(), /** * String representing the user-agent of the browser * @deprecated Use YAHOO.env.ua * @property browser * @type {String|Boolean} */ browser: function () { var ua = navigator.userAgent.toLowerCase(); /* Check Opera first in case of spoof and check Safari before Gecko since Safari's user agent string includes "like Gecko" */ if (ua.indexOf('opera') != -1) { return 'opera'; } else if (ua.indexOf('msie 7') != -1) { return 'ie7'; } else if (ua.indexOf('msie') != -1) { return 'ie'; } else if (ua.indexOf('safari') != -1) { return 'safari'; } else if (ua.indexOf('gecko') != -1) { return 'gecko'; } else { return false; } }(), /** * Boolean representing whether or not the current browsing context is * secure (https) * @property isSecure * @type Boolean */ isSecure: function () { if (window.location.href.toLowerCase().indexOf("https") === 0) { return true; } else { return false; } }(), /** * Initializes the custom events for Module which are fired * automatically at appropriate times by the Module class. */ initDefaultConfig: function () { // Add properties // /** * Specifies whether the Module is visible on the page. * @config visible * @type Boolean * @default true */ this.cfg.addProperty(DEFAULT_CONFIG.VISIBLE.key, { handler: this.configVisible, value: DEFAULT_CONFIG.VISIBLE.value, validator: DEFAULT_CONFIG.VISIBLE.validator }); /** * <p> * Object or array of objects representing the ContainerEffect * classes that are active for animating the container. * </p> * <p> * <strong>NOTE:</strong> Although this configuration * property is introduced at the Module level, an out of the box * implementation is not shipped for the Module class so setting * the proroperty on the Module class has no effect. The Overlay * class is the first class to provide out of the box ContainerEffect * support. * </p> * @config effect * @type Object * @default null */ this.cfg.addProperty(DEFAULT_CONFIG.EFFECT.key, { handler: this.configEffect, suppressEvent: DEFAULT_CONFIG.EFFECT.suppressEvent, supercedes: DEFAULT_CONFIG.EFFECT.supercedes }); /** * Specifies whether to create a special proxy iframe to monitor * for user font resizing in the document * @config monitorresize * @type Boolean * @default true */ this.cfg.addProperty(DEFAULT_CONFIG.MONITOR_RESIZE.key, { handler: this.configMonitorResize, value: DEFAULT_CONFIG.MONITOR_RESIZE.value }); /** * Specifies if the module should be rendered as the first child * of document.body or appended as the last child when render is called * with document.body as the "appendToNode". * <p> * Appending to the body while the DOM is still being constructed can * lead to Operation Aborted errors in IE hence this flag is set to * false by default. * </p> * * @config appendtodocumentbody * @type Boolean * @default false */ this.cfg.addProperty(DEFAULT_CONFIG.APPEND_TO_DOCUMENT_BODY.key, { value: DEFAULT_CONFIG.APPEND_TO_DOCUMENT_BODY.value }); }, /** * The Module class's initialization method, which is executed for * Module and all of its subclasses. This method is automatically * called by the constructor, and sets up all DOM references for * pre-existing markup, and creates required markup if it is not * already present. * <p> * If the element passed in does not have an id, one will be generated * for it. * </p> * @method init * @param {String} el The element ID representing the Module <em>OR</em> * @param {HTMLElement} el The element representing the Module * @param {Object} userConfig The configuration Object literal * containing the configuration that should be set for this module. * See configuration documentation for more details. */ init: function (el, userConfig) { var elId, child; this.initEvents(); this.beforeInitEvent.fire(Module); /** * The Module's Config object used for monitoring * configuration properties. * @property cfg * @type YAHOO.util.Config */ this.cfg = new Config(this); if (this.isSecure) { this.imageRoot = Module.IMG_ROOT_SSL; } if (typeof el == "string") { elId = el; el = document.getElementById(el); if (! el) { el = (createModuleTemplate()).cloneNode(false); el.id = elId; } } this.id = Dom.generateId(el); this.element = el; child = this.element.firstChild; if (child) { var fndHd = false, fndBd = false, fndFt = false; do { // We're looking for elements if (1 == child.nodeType) { if (!fndHd && Dom.hasClass(child, Module.CSS_HEADER)) { this.header = child; fndHd = true; } else if (!fndBd && Dom.hasClass(child, Module.CSS_BODY)) { this.body = child; fndBd = true; } else if (!fndFt && Dom.hasClass(child, Module.CSS_FOOTER)){ this.footer = child; fndFt = true; } } } while ((child = child.nextSibling)); } this.initDefaultConfig(); Dom.addClass(this.element, Module.CSS_MODULE); if (userConfig) { this.cfg.applyConfig(userConfig, true); } /* Subscribe to the fireQueue() method of Config so that any queued configuration changes are excecuted upon render of the Module */ if (!Config.alreadySubscribed(this.renderEvent, this.cfg.fireQueue, this.cfg)) { this.renderEvent.subscribe(this.cfg.fireQueue, this.cfg, true); } this.initEvent.fire(Module); }, /** * Initialize an empty IFRAME that is placed out of the visible area * that can be used to detect text resize. * @method initResizeMonitor */ initResizeMonitor: function () { var isGeckoWin = (UA.gecko && this.platform == "windows"); if (isGeckoWin) { // Help prevent spinning loading icon which // started with FireFox 2.0.0.8/Win var self = this; setTimeout(function(){self._initResizeMonitor();}, 0); } else { this._initResizeMonitor(); } }, /** * Create and initialize the text resize monitoring iframe. * * @protected * @method _initResizeMonitor */ _initResizeMonitor : function() { var oDoc, oIFrame, sHTML; function fireTextResize() { Module.textResizeEvent.fire(); } if (!UA.opera) { oIFrame = Dom.get("_yuiResizeMonitor"); var supportsCWResize = this._supportsCWResize(); if (!oIFrame) { oIFrame = document.createElement("iframe"); if (this.isSecure && Module.RESIZE_MONITOR_SECURE_URL && UA.ie) { oIFrame.src = Module.RESIZE_MONITOR_SECURE_URL; } if (!supportsCWResize) { // Can't monitor on contentWindow, so fire from inside iframe sHTML = ["<html><head><script ", "type=\"text/javascript\">", "window.onresize=function(){window.parent.", "YAHOO.widget.Module.textResizeEvent.", "fire();};<", "\/script></head>", "<body></body></html>"].join(''); oIFrame.src = "data:text/html;charset=utf-8," + encodeURIComponent(sHTML); } oIFrame.id = "_yuiResizeMonitor"; oIFrame.title = "Text Resize Monitor"; oIFrame.tabIndex = -1; oIFrame.setAttribute("role", "presentation"); /* Need to set "position" property before inserting the iframe into the document or Safari's status bar will forever indicate the iframe is loading (See YUILibrary bug #1723064) */ oIFrame.style.position = "absolute"; oIFrame.style.visibility = "hidden"; var db = document.body, fc = db.firstChild; if (fc) { db.insertBefore(oIFrame, fc); } else { db.appendChild(oIFrame); } // Setting the background color fixes an issue with IE6/IE7, where // elements in the DOM, with -ve margin-top which positioned them // offscreen (so they would be overlapped by the iframe and its -ve top // setting), would have their -ve margin-top ignored, when the iframe // was added. oIFrame.style.backgroundColor = "transparent"; oIFrame.style.borderWidth = "0"; oIFrame.style.width = "2em"; oIFrame.style.height = "2em"; oIFrame.style.left = "0"; oIFrame.style.top = (-1 * (oIFrame.offsetHeight + Module.RESIZE_MONITOR_BUFFER)) + "px"; oIFrame.style.visibility = "visible"; /* Don't open/close the document for Gecko like we used to, since it leads to duplicate cookies. (See YUILibrary bug #1721755) */ if (UA.webkit) { oDoc = oIFrame.contentWindow.document; oDoc.open(); oDoc.close(); } } if (oIFrame && oIFrame.contentWindow) { Module.textResizeEvent.subscribe(this.onDomResize, this, true); if (!Module.textResizeInitialized) { if (supportsCWResize) { if (!Event.on(oIFrame.contentWindow, "resize", fireTextResize)) { /* This will fail in IE if document.domain has changed, so we must change the listener to use the oIFrame element instead */ Event.on(oIFrame, "resize", fireTextResize); } } Module.textResizeInitialized = true; } this.resizeMonitor = oIFrame; } } }, /** * Text resize monitor helper method. * Determines if the browser supports resize events on iframe content windows. * * @private * @method _supportsCWResize */ _supportsCWResize : function() { /* Gecko 1.8.0 (FF1.5), 1.8.1.0-5 (FF2) won't fire resize on contentWindow. Gecko 1.8.1.6+ (FF2.0.0.6+) and all other browsers will fire resize on contentWindow. We don't want to start sniffing for patch versions, so fire textResize the same way on all FF2 flavors */ var bSupported = true; if (UA.gecko && UA.gecko <= 1.8) { bSupported = false; } return bSupported; }, /** * Event handler fired when the resize monitor element is resized. * @method onDomResize * @param {DOMEvent} e The DOM resize event * @param {Object} obj The scope object passed to the handler */ onDomResize: function (e, obj) { var nTop = -1 * (this.resizeMonitor.offsetHeight + Module.RESIZE_MONITOR_BUFFER); this.resizeMonitor.style.top = nTop + "px"; this.resizeMonitor.style.left = "0"; }, /** * Sets the Module's header content to the markup specified, or appends * the passed element to the header. * * If no header is present, one will * be automatically created. An empty string can be passed to the method * to clear the contents of the header. * * @method setHeader * @param {HTML} headerContent The markup used to set the header content. * As a convenience, non HTMLElement objects can also be passed into * the method, and will be treated as strings, with the header innerHTML * set to their default toString implementations. * * <p>NOTE: Markup passed into this method is added to the DOM as HTML, and should be escaped by the implementor if coming from an external source.</p> * * <em>OR</em> * @param {HTMLElement} headerContent The HTMLElement to append to * <em>OR</em> * @param {DocumentFragment} headerContent The document fragment * containing elements which are to be added to the header */ setHeader: function (headerContent) { var oHeader = this.header || (this.header = createHeader()); if (headerContent.nodeName) { oHeader.innerHTML = ""; oHeader.appendChild(headerContent); } else { oHeader.innerHTML = headerContent; } if (this._rendered) { this._renderHeader(); } this.changeHeaderEvent.fire(headerContent); this.changeContentEvent.fire(); }, /** * Appends the passed element to the header. If no header is present, * one will be automatically created. * @method appendToHeader * @param {HTMLElement | DocumentFragment} element The element to * append to the header. In the case of a document fragment, the * children of the fragment will be appended to the header. */ appendToHeader: function (element) { var oHeader = this.header || (this.header = createHeader()); oHeader.appendChild(element); this.changeHeaderEvent.fire(element); this.changeContentEvent.fire(); }, /** * Sets the Module's body content to the HTML specified. * * If no body is present, one will be automatically created. * * An empty string can be passed to the method to clear the contents of the body. * @method setBody * @param {HTML} bodyContent The HTML used to set the body content * As a convenience, non HTMLElement objects can also be passed into * the method, and will be treated as strings, with the body innerHTML * set to their default toString implementations. * * <p>NOTE: Markup passed into this method is added to the DOM as HTML, and should be escaped by the implementor if coming from an external source.</p> * * <em>OR</em> * @param {HTMLElement} bodyContent The HTMLElement to add as the first and only * child of the body element. * <em>OR</em> * @param {DocumentFragment} bodyContent The document fragment * containing elements which are to be added to the body */ setBody: function (bodyContent) { var oBody = this.body || (this.body = createBody()); if (bodyContent.nodeName) { oBody.innerHTML = ""; oBody.appendChild(bodyContent); } else { oBody.innerHTML = bodyContent; } if (this._rendered) { this._renderBody(); } this.changeBodyEvent.fire(bodyContent); this.changeContentEvent.fire(); }, /** * Appends the passed element to the body. If no body is present, one * will be automatically created. * @method appendToBody * @param {HTMLElement | DocumentFragment} element The element to * append to the body. In the case of a document fragment, the * children of the fragment will be appended to the body. * */ appendToBody: function (element) { var oBody = this.body || (this.body = createBody()); oBody.appendChild(element); this.changeBodyEvent.fire(element); this.changeContentEvent.fire(); }, /** * Sets the Module's footer content to the HTML specified, or appends * the passed element to the footer. If no footer is present, one will * be automatically created. An empty string can be passed to the method * to clear the contents of the footer. * @method setFooter * @param {HTML} footerContent The HTML used to set the footer * As a convenience, non HTMLElement objects can also be passed into * the method, and will be treated as strings, with the footer innerHTML * set to their default toString implementations. * * <p>NOTE: Markup passed into this method is added to the DOM as HTML, and should be escaped by the implementor if coming from an external source.</p> * * <em>OR</em> * @param {HTMLElement} footerContent The HTMLElement to append to * the footer * <em>OR</em> * @param {DocumentFragment} footerContent The document fragment containing * elements which are to be added to the footer */ setFooter: function (footerContent) { var oFooter = this.footer || (this.footer = createFooter()); if (footerContent.nodeName) { oFooter.innerHTML = ""; oFooter.appendChild(footerContent); } else { oFooter.innerHTML = footerContent; } if (this._rendered) { this._renderFooter(); } this.changeFooterEvent.fire(footerContent); this.changeContentEvent.fire(); }, /** * Appends the passed element to the footer. If no footer is present, * one will be automatically created. * @method appendToFooter * @param {HTMLElement | DocumentFragment} element The element to * append to the footer. In the case of a document fragment, the * children of the fragment will be appended to the footer */ appendToFooter: function (element) { var oFooter = this.footer || (this.footer = createFooter()); oFooter.appendChild(element); this.changeFooterEvent.fire(element); this.changeContentEvent.fire(); }, /** * Renders the Module by inserting the elements that are not already * in the main Module into their correct places. Optionally appends * the Module to the specified node prior to the render's execution. * <p> * For Modules without existing markup, the appendToNode argument * is REQUIRED. If this argument is ommitted and the current element is * not present in the document, the function will return false, * indicating that the render was a failure. * </p> * <p> * NOTE: As of 2.3.1, if the appendToNode is the document's body element * then the module is rendered as the first child of the body element, * and not appended to it, to avoid Operation Aborted errors in IE when * rendering the module before window's load event is fired. You can * use the appendtodocumentbody configuration property to change this * to append to document.body if required. * </p> * @method render * @param {String} appendToNode The element id to which the Module * should be appended to prior to rendering <em>OR</em> * @param {HTMLElement} appendToNode The element to which the Module * should be appended to prior to rendering * @param {HTMLElement} moduleElement OPTIONAL. The element that * represents the actual Standard Module container. * @return {Boolean} Success or failure of the render */ render: function (appendToNode, moduleElement) { var me = this; function appendTo(parentNode) { if (typeof parentNode == "string") { parentNode = document.getElementById(parentNode); } if (parentNode) { me._addToParent(parentNode, me.element); me.appendEvent.fire(); } } this.beforeRenderEvent.fire(); if (! moduleElement) { moduleElement = this.element; } if (appendToNode) { appendTo(appendToNode); } else { // No node was passed in. If the element is not already in the Dom, this fails if (! Dom.inDocument(this.element)) { YAHOO.log("Render failed. Must specify appendTo node if " + " Module isn't already in the DOM.", "error"); return false; } } this._renderHeader(moduleElement); this._renderBody(moduleElement); this._renderFooter(moduleElement); this._rendered = true; this.renderEvent.fire(); return true; }, /** * Renders the currently set header into it's proper position under the * module element. If the module element is not provided, "this.element" * is used. * * @method _renderHeader * @protected * @param {HTMLElement} moduleElement Optional. A reference to the module element */ _renderHeader: function(moduleElement){ moduleElement = moduleElement || this.element; // Need to get everything into the DOM if it isn't already if (this.header && !Dom.inDocument(this.header)) { // There is a header, but it's not in the DOM yet. Need to add it. var firstChild = moduleElement.firstChild; if (firstChild) { moduleElement.insertBefore(this.header, firstChild); } else { moduleElement.appendChild(this.header); } } }, /** * Renders the currently set body into it's proper position under the * module element. If the module element is not provided, "this.element" * is used. * * @method _renderBody * @protected * @param {HTMLElement} moduleElement Optional. A reference to the module element. */ _renderBody: function(moduleElement){ moduleElement = moduleElement || this.element; if (this.body && !Dom.inDocument(this.body)) { // There is a body, but it's not in the DOM yet. Need to add it. if (this.footer && Dom.isAncestor(moduleElement, this.footer)) { moduleElement.insertBefore(this.body, this.footer); } else { moduleElement.appendChild(this.body); } } }, /** * Renders the currently set footer into it's proper position under the * module element. If the module element is not provided, "this.element" * is used. * * @method _renderFooter * @protected * @param {HTMLElement} moduleElement Optional. A reference to the module element */ _renderFooter: function(moduleElement){ moduleElement = moduleElement || this.element; if (this.footer && !Dom.inDocument(this.footer)) { // There is a footer, but it's not in the DOM yet. Need to add it. moduleElement.appendChild(this.footer); } }, /** * Removes the Module element from the DOM, sets all child elements to null, and purges the bounding element of event listeners. * @method destroy * @param {boolean} shallowPurge If true, only the parent element's DOM event listeners are purged. If false, or not provided, all children are also purged of DOM event listeners. * NOTE: The flag is a "shallowPurge" flag, as opposed to what may be a more intuitive "purgeChildren" flag to maintain backwards compatibility with behavior prior to 2.9.0. */ destroy: function (shallowPurge) { var parent, purgeChildren = !(shallowPurge); if (this.element) { Event.purgeElement(this.element, purgeChildren); parent = this.element.parentNode; } if (parent) { parent.removeChild(this.element); } this.element = null; this.header = null; this.body = null; this.footer = null; Module.textResizeEvent.unsubscribe(this.onDomResize, this); this.cfg.destroy(); this.cfg = null; this.destroyEvent.fire(); }, /** * Shows the Module element by setting the visible configuration * property to true. Also fires two events: beforeShowEvent prior to * the visibility change, and showEvent after. * @method show */ show: function () { this.cfg.setProperty("visible", true); }, /** * Hides the Module element by setting the visible configuration * property to false. Also fires two events: beforeHideEvent prior to * the visibility change, and hideEvent after. * @method hide */ hide: function () { this.cfg.setProperty("visible", false); }, // BUILT-IN EVENT HANDLERS FOR MODULE // /** * Default event handler for changing the visibility property of a * Module. By default, this is achieved by switching the "display" style * between "block" and "none". * This method is responsible for firing showEvent and hideEvent. * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. * @method configVisible */ configVisible: function (type, args, obj) { var visible = args[0]; if (visible) { if(this.beforeShowEvent.fire()) { Dom.setStyle(this.element, "display", "block"); this.showEvent.fire(); } } else { if (this.beforeHideEvent.fire()) { Dom.setStyle(this.element, "display", "none"); this.hideEvent.fire(); } } }, /** * Default event handler for the "effect" configuration property * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. * @method configEffect */ configEffect: function (type, args, obj) { this._cachedEffects = (this.cacheEffects) ? this._createEffects(args[0]) : null; }, /** * If true, ContainerEffects (and Anim instances) are cached when "effect" is set, and reused. * If false, new instances are created each time the container is hidden or shown, as was the * behavior prior to 2.9.0. * * @property cacheEffects * @since 2.9.0 * @default true * @type boolean */ cacheEffects : true, /** * Creates an array of ContainerEffect instances from the provided configs * * @method _createEffects * @param {Array|Object} effectCfg An effect configuration or array of effect configurations * @return {Array} An array of ContainerEffect instances. * @protected */ _createEffects: function(effectCfg) { var effectInstances = null, n, i, eff; if (effectCfg) { if (effectCfg instanceof Array) { effectInstances = []; n = effectCfg.length; for (i = 0; i < n; i++) { eff = effectCfg[i]; if (eff.effect) { effectInstances[effectInstances.length] = eff.effect(this, eff.duration); } } } else if (effectCfg.effect) { effectInstances = [effectCfg.effect(this, effectCfg.duration)]; } } return effectInstances; }, /** * Default event handler for the "monitorresize" configuration property * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. * @method configMonitorResize */ configMonitorResize: function (type, args, obj) { var monitor = args[0]; if (monitor) { this.initResizeMonitor(); } else { Module.textResizeEvent.unsubscribe(this.onDomResize, this, true); this.resizeMonitor = null; } }, /** * This method is a protected helper, used when constructing the DOM structure for the module * to account for situations which may cause Operation Aborted errors in IE. It should not * be used for general DOM construction. * <p> * If the parentNode is not document.body, the element is appended as the last element. * </p> * <p> * If the parentNode is document.body the element is added as the first child to help * prevent Operation Aborted errors in IE. * </p> * * @param {parentNode} The HTML element to which the element will be added * @param {element} The HTML element to be added to parentNode's children * @method _addToParent * @protected */ _addToParent: function(parentNode, element) { if (!this.cfg.getProperty("appendtodocumentbody") && parentNode === document.body && parentNode.firstChild) { parentNode.insertBefore(element, parentNode.firstChild); } else { parentNode.appendChild(element); } }, /** * Returns a String representation of the Object. * @method toString * @return {String} The string representation of the Module */ toString: function () { return "Module " + this.id; } }; YAHOO.lang.augmentProto(Module, YAHOO.util.EventProvider); }()); (function () { /** * Overlay is a Module that is absolutely positioned above the page flow. It * has convenience methods for positioning and sizing, as well as options for * controlling zIndex and constraining the Overlay's position to the current * visible viewport. Overlay also contains a dynamicly generated IFRAME which * is placed beneath it for Internet Explorer 6 and 5.x so that it will be * properly rendered above SELECT elements. * @namespace YAHOO.widget * @class Overlay * @extends YAHOO.widget.Module * @param {String} el The element ID representing the Overlay <em>OR</em> * @param {HTMLElement} el The element representing the Overlay * @param {Object} userConfig The configuration object literal containing * the configuration that should be set for this Overlay. See configuration * documentation for more details. * @constructor */ YAHOO.widget.Overlay = function (el, userConfig) { YAHOO.widget.Overlay.superclass.constructor.call(this, el, userConfig); }; var Lang = YAHOO.lang, CustomEvent = YAHOO.util.CustomEvent, Module = YAHOO.widget.Module, Event = YAHOO.util.Event, Dom = YAHOO.util.Dom, Config = YAHOO.util.Config, UA = YAHOO.env.ua, Overlay = YAHOO.widget.Overlay, _SUBSCRIBE = "subscribe", _UNSUBSCRIBE = "unsubscribe", _CONTAINED = "contained", m_oIFrameTemplate, /** * Constant representing the name of the Overlay's events * @property EVENT_TYPES * @private * @final * @type Object */ EVENT_TYPES = { "BEFORE_MOVE": "beforeMove", "MOVE": "move" }, /** * Constant representing the Overlay's configuration properties * @property DEFAULT_CONFIG * @private * @final * @type Object */ DEFAULT_CONFIG = { "X": { key: "x", validator: Lang.isNumber, suppressEvent: true, supercedes: ["iframe"] }, "Y": { key: "y", validator: Lang.isNumber, suppressEvent: true, supercedes: ["iframe"] }, "XY": { key: "xy", suppressEvent: true, supercedes: ["iframe"] }, "CONTEXT": { key: "context", suppressEvent: true, supercedes: ["iframe"] }, "FIXED_CENTER": { key: "fixedcenter", value: false, supercedes: ["iframe", "visible"] }, "WIDTH": { key: "width", suppressEvent: true, supercedes: ["context", "fixedcenter", "iframe"] }, "HEIGHT": { key: "height", suppressEvent: true, supercedes: ["context", "fixedcenter", "iframe"] }, "AUTO_FILL_HEIGHT" : { key: "autofillheight", supercedes: ["height"], value:"body" }, "ZINDEX": { key: "zindex", value: null }, "CONSTRAIN_TO_VIEWPORT": { key: "constraintoviewport", value: false, validator: Lang.isBoolean, supercedes: ["iframe", "x", "y", "xy"] }, "IFRAME": { key: "iframe", value: (UA.ie == 6 ? true : false), validator: Lang.isBoolean, supercedes: ["zindex"] }, "PREVENT_CONTEXT_OVERLAP": { key: "preventcontextoverlap", value: false, validator: Lang.isBoolean, supercedes: ["constraintoviewport"] } }; /** * The URL that will be placed in the iframe * @property YAHOO.widget.Overlay.IFRAME_SRC * @static * @final * @type String */ Overlay.IFRAME_SRC = "javascript:false;"; /** * Number representing how much the iframe shim should be offset from each * side of an Overlay instance, in pixels. * @property YAHOO.widget.Overlay.IFRAME_SRC * @default 3 * @static * @final * @type Number */ Overlay.IFRAME_OFFSET = 3; /** * Number representing the minimum distance an Overlay instance should be * positioned relative to the boundaries of the browser's viewport, in pixels. * @property YAHOO.widget.Overlay.VIEWPORT_OFFSET * @default 10 * @static * @final * @type Number */ Overlay.VIEWPORT_OFFSET = 10; /** * Constant representing the top left corner of an element, used for * configuring the context element alignment * @property YAHOO.widget.Overlay.TOP_LEFT * @static * @final * @type String */ Overlay.TOP_LEFT = "tl"; /** * Constant representing the top right corner of an element, used for * configuring the context element alignment * @property YAHOO.widget.Overlay.TOP_RIGHT * @static * @final * @type String */ Overlay.TOP_RIGHT = "tr"; /** * Constant representing the top bottom left corner of an element, used for * configuring the context element alignment * @property YAHOO.widget.Overlay.BOTTOM_LEFT * @static * @final * @type String */ Overlay.BOTTOM_LEFT = "bl"; /** * Constant representing the bottom right corner of an element, used for * configuring the context element alignment * @property YAHOO.widget.Overlay.BOTTOM_RIGHT * @static * @final * @type String */ Overlay.BOTTOM_RIGHT = "br"; Overlay.PREVENT_OVERLAP_X = { "tltr": true, "blbr": true, "brbl": true, "trtl": true }; Overlay.PREVENT_OVERLAP_Y = { "trbr": true, "tlbl": true, "bltl": true, "brtr": true }; /** * Constant representing the default CSS class used for an Overlay * @property YAHOO.widget.Overlay.CSS_OVERLAY * @static * @final * @type String */ Overlay.CSS_OVERLAY = "yui-overlay"; /** * Constant representing the default hidden CSS class used for an Overlay. This class is * applied to the overlay's outer DIV whenever it's hidden. * * @property YAHOO.widget.Overlay.CSS_HIDDEN * @static * @final * @type String */ Overlay.CSS_HIDDEN = "yui-overlay-hidden"; /** * Constant representing the default CSS class used for an Overlay iframe shim. * * @property YAHOO.widget.Overlay.CSS_IFRAME * @static * @final * @type String */ Overlay.CSS_IFRAME = "yui-overlay-iframe"; /** * Constant representing the names of the standard module elements * used in the overlay. * @property YAHOO.widget.Overlay.STD_MOD_RE * @static * @final * @type RegExp */ Overlay.STD_MOD_RE = /^\s*?(body|footer|header)\s*?$/i; /** * A singleton CustomEvent used for reacting to the DOM event for * window scroll * @event YAHOO.widget.Overlay.windowScrollEvent */ Overlay.windowScrollEvent = new CustomEvent("windowScroll"); /** * A singleton CustomEvent used for reacting to the DOM event for * window resize * @event YAHOO.widget.Overlay.windowResizeEvent */ Overlay.windowResizeEvent = new CustomEvent("windowResize"); /** * The DOM event handler used to fire the CustomEvent for window scroll * @method YAHOO.widget.Overlay.windowScrollHandler * @static * @param {DOMEvent} e The DOM scroll event */ Overlay.windowScrollHandler = function (e) { var t = Event.getTarget(e); // - Webkit (Safari 2/3) and Opera 9.2x bubble scroll events from elements to window // - FF2/3 and IE6/7, Opera 9.5x don't bubble scroll events from elements to window // - IE doesn't recognize scroll registered on the document. // // Also, when document view is scrolled, IE doesn't provide a target, // rest of the browsers set target to window.document, apart from opera // which sets target to window. if (!t || t === window || t === window.document) { if (UA.ie) { if (! window.scrollEnd) { window.scrollEnd = -1; } clearTimeout(window.scrollEnd); window.scrollEnd = setTimeout(function () { Overlay.windowScrollEvent.fire(); }, 1); } else { Overlay.windowScrollEvent.fire(); } } }; /** * The DOM event handler used to fire the CustomEvent for window resize * @method YAHOO.widget.Overlay.windowResizeHandler * @static * @param {DOMEvent} e The DOM resize event */ Overlay.windowResizeHandler = function (e) { if (UA.ie) { if (! window.resizeEnd) { window.resizeEnd = -1; } clearTimeout(window.resizeEnd); window.resizeEnd = setTimeout(function () { Overlay.windowResizeEvent.fire(); }, 100); } else { Overlay.windowResizeEvent.fire(); } }; /** * A boolean that indicated whether the window resize and scroll events have * already been subscribed to. * @property YAHOO.widget.Overlay._initialized * @private * @type Boolean */ Overlay._initialized = null; if (Overlay._initialized === null) { Event.on(window, "scroll", Overlay.windowScrollHandler); Event.on(window, "resize", Overlay.windowResizeHandler); Overlay._initialized = true; } /** * Internal map of special event types, which are provided * by the instance. It maps the event type to the custom event * instance. Contains entries for the "windowScroll", "windowResize" and * "textResize" static container events. * * @property YAHOO.widget.Overlay._TRIGGER_MAP * @type Object * @static * @private */ Overlay._TRIGGER_MAP = { "windowScroll" : Overlay.windowScrollEvent, "windowResize" : Overlay.windowResizeEvent, "textResize" : Module.textResizeEvent }; YAHOO.extend(Overlay, Module, { /** * <p> * Array of default event types which will trigger * context alignment for the Overlay class. * </p> * <p>The array is empty by default for Overlay, * but maybe populated in future releases, so classes extending * Overlay which need to define their own set of CONTEXT_TRIGGERS * should concatenate their super class's prototype.CONTEXT_TRIGGERS * value with their own array of values. * </p> * <p> * E.g.: * <code>CustomOverlay.prototype.CONTEXT_TRIGGERS = YAHOO.widget.Overlay.prototype.CONTEXT_TRIGGERS.concat(["windowScroll"]);</code> * </p> * * @property CONTEXT_TRIGGERS * @type Array * @final */ CONTEXT_TRIGGERS : [], /** * The Overlay initialization method, which is executed for Overlay and * all of its subclasses. This method is automatically called by the * constructor, and sets up all DOM references for pre-existing markup, * and creates required markup if it is not already present. * @method init * @param {String} el The element ID representing the Overlay <em>OR</em> * @param {HTMLElement} el The element representing the Overlay * @param {Object} userConfig The configuration object literal * containing the configuration that should be set for this Overlay. * See configuration documentation for more details. */ init: function (el, userConfig) { /* Note that we don't pass the user config in here yet because we only want it executed once, at the lowest subclass level */ Overlay.superclass.init.call(this, el/*, userConfig*/); this.beforeInitEvent.fire(Overlay); Dom.addClass(this.element, Overlay.CSS_OVERLAY); if (userConfig) { this.cfg.applyConfig(userConfig, true); } if (this.platform == "mac" && UA.gecko) { if (! Config.alreadySubscribed(this.showEvent, this.showMacGeckoScrollbars, this)) { this.showEvent.subscribe(this.showMacGeckoScrollbars, this, true); } if (! Config.alreadySubscribed(this.hideEvent, this.hideMacGeckoScrollbars, this)) { this.hideEvent.subscribe(this.hideMacGeckoScrollbars, this, true); } } this.initEvent.fire(Overlay); }, /** * Initializes the custom events for Overlay which are fired * automatically at appropriate times by the Overlay class. * @method initEvents */ initEvents: function () { Overlay.superclass.initEvents.call(this); var SIGNATURE = CustomEvent.LIST; /** * CustomEvent fired before the Overlay is moved. * @event beforeMoveEvent * @param {Number} x x coordinate * @param {Number} y y coordinate */ this.beforeMoveEvent = this.createEvent(EVENT_TYPES.BEFORE_MOVE); this.beforeMoveEvent.signature = SIGNATURE; /** * CustomEvent fired after the Overlay is moved. * @event moveEvent * @param {Number} x x coordinate * @param {Number} y y coordinate */ this.moveEvent = this.createEvent(EVENT_TYPES.MOVE); this.moveEvent.signature = SIGNATURE; }, /** * Initializes the class's configurable properties which can be changed * using the Overlay's Config object (cfg). * @method initDefaultConfig */ initDefaultConfig: function () { Overlay.superclass.initDefaultConfig.call(this); var cfg = this.cfg; // Add overlay config properties // /** * The absolute x-coordinate position of the Overlay * @config x * @type Number * @default null */ cfg.addProperty(DEFAULT_CONFIG.X.key, { handler: this.configX, validator: DEFAULT_CONFIG.X.validator, suppressEvent: DEFAULT_CONFIG.X.suppressEvent, supercedes: DEFAULT_CONFIG.X.supercedes }); /** * The absolute y-coordinate position of the Overlay * @config y * @type Number * @default null */ cfg.addProperty(DEFAULT_CONFIG.Y.key, { handler: this.configY, validator: DEFAULT_CONFIG.Y.validator, suppressEvent: DEFAULT_CONFIG.Y.suppressEvent, supercedes: DEFAULT_CONFIG.Y.supercedes }); /** * An array with the absolute x and y positions of the Overlay * @config xy * @type Number[] * @default null */ cfg.addProperty(DEFAULT_CONFIG.XY.key, { handler: this.configXY, suppressEvent: DEFAULT_CONFIG.XY.suppressEvent, supercedes: DEFAULT_CONFIG.XY.supercedes }); /** * <p> * The array of context arguments for context-sensitive positioning. * </p> * * <p> * The format of the array is: <code>[contextElementOrId, overlayCorner, contextCorner, arrayOfTriggerEvents (optional), xyOffset (optional)]</code>, the * the 5 array elements described in detail below: * </p> * * <dl> * <dt>contextElementOrId &#60;String|HTMLElement&#62;</dt> * <dd>A reference to the context element to which the overlay should be aligned (or it's id).</dd> * <dt>overlayCorner &#60;String&#62;</dt> * <dd>The corner of the overlay which is to be used for alignment. This corner will be aligned to the * corner of the context element defined by the "contextCorner" entry which follows. Supported string values are: * "tr" (top right), "tl" (top left), "br" (bottom right), or "bl" (bottom left).</dd> * <dt>contextCorner &#60;String&#62;</dt> * <dd>The corner of the context element which is to be used for alignment. Supported string values are the same ones listed for the "overlayCorner" entry above.</dd> * <dt>arrayOfTriggerEvents (optional) &#60;Array[String|CustomEvent]&#62;</dt> * <dd> * <p> * By default, context alignment is a one time operation, aligning the Overlay to the context element when context configuration property is set, or when the <a href="#method_align">align</a> * method is invoked. However, you can use the optional "arrayOfTriggerEvents" entry to define the list of events which should force the overlay to re-align itself with the context element. * This is useful in situations where the layout of the document may change, resulting in the context element's position being modified. * </p> * <p> * The array can contain either event type strings for events the instance publishes (e.g. "beforeShow") or CustomEvent instances. Additionally the following * 3 static container event types are also currently supported : <code>"windowResize", "windowScroll", "textResize"</code> (defined in <a href="#property__TRIGGER_MAP">_TRIGGER_MAP</a> private property). * </p> * </dd> * <dt>xyOffset &#60;Number[]&#62;</dt> * <dd> * A 2 element Array specifying the X and Y pixel amounts by which the Overlay should be offset from the aligned corner. e.g. [5,0] offsets the Overlay 5 pixels to the left, <em>after</em> aligning the given context corners. * NOTE: If using this property and no triggers need to be defined, the arrayOfTriggerEvents property should be set to null to maintain correct array positions for the arguments. * </dd> * </dl> * * <p> * For example, setting this property to <code>["img1", "tl", "bl"]</code> will * align the Overlay's top left corner to the bottom left corner of the * context element with id "img1". * </p> * <p> * Setting this property to <code>["img1", "tl", "bl", null, [0,5]</code> will * align the Overlay's top left corner to the bottom left corner of the * context element with id "img1", and then offset it by 5 pixels on the Y axis (providing a 5 pixel gap between the bottom of the context element and top of the overlay). * </p> * <p> * Adding the optional trigger values: <code>["img1", "tl", "bl", ["beforeShow", "windowResize"], [0,5]]</code>, * will re-align the overlay position, whenever the "beforeShow" or "windowResize" events are fired. * </p> * * @config context * @type Array * @default null */ cfg.addProperty(DEFAULT_CONFIG.CONTEXT.key, { handler: this.configContext, suppressEvent: DEFAULT_CONFIG.CONTEXT.suppressEvent, supercedes: DEFAULT_CONFIG.CONTEXT.supercedes }); /** * Determines whether or not the Overlay should be anchored * to the center of the viewport. * * <p>This property can be set to:</p> * * <dl> * <dt>true</dt> * <dd> * To enable fixed center positioning * <p> * When enabled, the overlay will * be positioned in the center of viewport when initially displayed, and * will remain in the center of the viewport whenever the window is * scrolled or resized. * </p> * <p> * If the overlay is too big for the viewport, * it's top left corner will be aligned with the top left corner of the viewport. * </p> * </dd> * <dt>false</dt> * <dd> * To disable fixed center positioning. * <p>In this case the overlay can still be * centered as a one-off operation, by invoking the <code>center()</code> method, * however it will not remain centered when the window is scrolled/resized. * </dd> * <dt>"contained"<dt> * <dd>To enable fixed center positioning, as with the <code>true</code> option. * <p>However, unlike setting the property to <code>true</code>, * when the property is set to <code>"contained"</code>, if the overlay is * too big for the viewport, it will not get automatically centered when the * user scrolls or resizes the window (until the window is large enough to contain the * overlay). This is useful in cases where the Overlay has both header and footer * UI controls which the user may need to access. * </p> * </dd> * </dl> * * @config fixedcenter * @type Boolean | String * @default false */ cfg.addProperty(DEFAULT_CONFIG.FIXED_CENTER.key, { handler: this.configFixedCenter, value: DEFAULT_CONFIG.FIXED_CENTER.value, validator: DEFAULT_CONFIG.FIXED_CENTER.validator, supercedes: DEFAULT_CONFIG.FIXED_CENTER.supercedes }); /** * CSS width of the Overlay. * @config width * @type String * @default null */ cfg.addProperty(DEFAULT_CONFIG.WIDTH.key, { handler: this.configWidth, suppressEvent: DEFAULT_CONFIG.WIDTH.suppressEvent, supercedes: DEFAULT_CONFIG.WIDTH.supercedes }); /** * CSS height of the Overlay. * @config height * @type String * @default null */ cfg.addProperty(DEFAULT_CONFIG.HEIGHT.key, { handler: this.configHeight, suppressEvent: DEFAULT_CONFIG.HEIGHT.suppressEvent, supercedes: DEFAULT_CONFIG.HEIGHT.supercedes }); /** * Standard module element which should auto fill out the height of the Overlay if the height config property is set. * Supported values are "header", "body", "footer". * * @config autofillheight * @type String * @default null */ cfg.addProperty(DEFAULT_CONFIG.AUTO_FILL_HEIGHT.key, { handler: this.configAutoFillHeight, value : DEFAULT_CONFIG.AUTO_FILL_HEIGHT.value, validator : this._validateAutoFill, supercedes: DEFAULT_CONFIG.AUTO_FILL_HEIGHT.supercedes }); /** * CSS z-index of the Overlay. * @config zIndex * @type Number * @default null */ cfg.addProperty(DEFAULT_CONFIG.ZINDEX.key, { handler: this.configzIndex, value: DEFAULT_CONFIG.ZINDEX.value }); /** * True if the Overlay should be prevented from being positioned * out of the viewport. * @config constraintoviewport * @type Boolean * @default false */ cfg.addProperty(DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.key, { handler: this.configConstrainToViewport, value: DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.value, validator: DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.validator, supercedes: DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.supercedes }); /** * @config iframe * @description Boolean indicating whether or not the Overlay should * have an IFRAME shim; used to prevent SELECT elements from * poking through an Overlay instance in IE6. When set to "true", * the iframe shim is created when the Overlay instance is intially * made visible. * @type Boolean * @default true for IE6 and below, false for all other browsers. */ cfg.addProperty(DEFAULT_CONFIG.IFRAME.key, { handler: this.configIframe, value: DEFAULT_CONFIG.IFRAME.value, validator: DEFAULT_CONFIG.IFRAME.validator, supercedes: DEFAULT_CONFIG.IFRAME.supercedes }); /** * @config preventcontextoverlap * @description Boolean indicating whether or not the Overlay should overlap its * context element (defined using the "context" configuration property) when the * "constraintoviewport" configuration property is set to "true". * @type Boolean * @default false */ cfg.addProperty(DEFAULT_CONFIG.PREVENT_CONTEXT_OVERLAP.key, { value: DEFAULT_CONFIG.PREVENT_CONTEXT_OVERLAP.value, validator: DEFAULT_CONFIG.PREVENT_CONTEXT_OVERLAP.validator, supercedes: DEFAULT_CONFIG.PREVENT_CONTEXT_OVERLAP.supercedes }); }, /** * Moves the Overlay to the specified position. This function is * identical to calling this.cfg.setProperty("xy", [x,y]); * @method moveTo * @param {Number} x The Overlay's new x position * @param {Number} y The Overlay's new y position */ moveTo: function (x, y) { this.cfg.setProperty("xy", [x, y]); }, /** * Adds a CSS class ("hide-scrollbars") and removes a CSS class * ("show-scrollbars") to the Overlay to fix a bug in Gecko on Mac OS X * (https://bugzilla.mozilla.org/show_bug.cgi?id=187435) * @method hideMacGeckoScrollbars */ hideMacGeckoScrollbars: function () { Dom.replaceClass(this.element, "show-scrollbars", "hide-scrollbars"); }, /** * Adds a CSS class ("show-scrollbars") and removes a CSS class * ("hide-scrollbars") to the Overlay to fix a bug in Gecko on Mac OS X * (https://bugzilla.mozilla.org/show_bug.cgi?id=187435) * @method showMacGeckoScrollbars */ showMacGeckoScrollbars: function () { Dom.replaceClass(this.element, "hide-scrollbars", "show-scrollbars"); }, /** * Internal implementation to set the visibility of the overlay in the DOM. * * @method _setDomVisibility * @param {boolean} visible Whether to show or hide the Overlay's outer element * @protected */ _setDomVisibility : function(show) { Dom.setStyle(this.element, "visibility", (show) ? "visible" : "hidden"); var hiddenClass = Overlay.CSS_HIDDEN; if (show) { Dom.removeClass(this.element, hiddenClass); } else { Dom.addClass(this.element, hiddenClass); } }, // BEGIN BUILT-IN PROPERTY EVENT HANDLERS // /** * The default event handler fired when the "visible" property is * changed. This method is responsible for firing showEvent * and hideEvent. * @method configVisible * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configVisible: function (type, args, obj) { var visible = args[0], currentVis = Dom.getStyle(this.element, "visibility"), effects = this._cachedEffects || this._createEffects(this.cfg.getProperty("effect")), isMacGecko = (this.platform == "mac" && UA.gecko), alreadySubscribed = Config.alreadySubscribed, ei, e, j, k, h, nEffectInstances; if (currentVis == "inherit") { e = this.element.parentNode; while (e.nodeType != 9 && e.nodeType != 11) { currentVis = Dom.getStyle(e, "visibility"); if (currentVis != "inherit") { break; } e = e.parentNode; } if (currentVis == "inherit") { currentVis = "visible"; } } if (visible) { // Show if (isMacGecko) { this.showMacGeckoScrollbars(); } if (effects) { // Animate in if (visible) { // Animate in if not showing // Fading out is a bit of a hack, but didn't want to risk doing // something broader (e.g a generic this._animatingOut) for 2.9.0 if (currentVis != "visible" || currentVis === "" || this._fadingOut) { if (this.beforeShowEvent.fire()) { nEffectInstances = effects.length; for (j = 0; j < nEffectInstances; j++) { ei = effects[j]; if (j === 0 && !alreadySubscribed(ei.animateInCompleteEvent, this.showEvent.fire, this.showEvent)) { ei.animateInCompleteEvent.subscribe(this.showEvent.fire, this.showEvent, true); } ei.animateIn(); } } } } } else { // Show if (currentVis != "visible" || currentVis === "") { if (this.beforeShowEvent.fire()) { this._setDomVisibility(true); this.cfg.refireEvent("iframe"); this.showEvent.fire(); } } else { this._setDomVisibility(true); } } } else { // Hide if (isMacGecko) { this.hideMacGeckoScrollbars(); } if (effects) { // Animate out if showing if (currentVis == "visible" || this._fadingIn) { if (this.beforeHideEvent.fire()) { nEffectInstances = effects.length; for (k = 0; k < nEffectInstances; k++) { h = effects[k]; if (k === 0 && !alreadySubscribed(h.animateOutCompleteEvent, this.hideEvent.fire, this.hideEvent)) { h.animateOutCompleteEvent.subscribe(this.hideEvent.fire, this.hideEvent, true); } h.animateOut(); } } } else if (currentVis === "") { this._setDomVisibility(false); } } else { // Simple hide if (currentVis == "visible" || currentVis === "") { if (this.beforeHideEvent.fire()) { this._setDomVisibility(false); this.hideEvent.fire(); } } else { this._setDomVisibility(false); } } } }, /** * Fixed center event handler used for centering on scroll/resize, but only if * the overlay is visible and, if "fixedcenter" is set to "contained", only if * the overlay fits within the viewport. * * @method doCenterOnDOMEvent */ doCenterOnDOMEvent: function () { var cfg = this.cfg, fc = cfg.getProperty("fixedcenter"); if (cfg.getProperty("visible")) { if (fc && (fc !== _CONTAINED || this.fitsInViewport())) { this.center(); } } }, /** * Determines if the Overlay (including the offset value defined by Overlay.VIEWPORT_OFFSET) * will fit entirely inside the viewport, in both dimensions - width and height. * * @method fitsInViewport * @return boolean true if the Overlay will fit, false if not */ fitsInViewport : function() { var nViewportOffset = Overlay.VIEWPORT_OFFSET, element = this.element, elementWidth = element.offsetWidth, elementHeight = element.offsetHeight, viewportWidth = Dom.getViewportWidth(), viewportHeight = Dom.getViewportHeight(); return ((elementWidth + nViewportOffset < viewportWidth) && (elementHeight + nViewportOffset < viewportHeight)); }, /** * The default event handler fired when the "fixedcenter" property * is changed. * @method configFixedCenter * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configFixedCenter: function (type, args, obj) { var val = args[0], alreadySubscribed = Config.alreadySubscribed, windowResizeEvent = Overlay.windowResizeEvent, windowScrollEvent = Overlay.windowScrollEvent; if (val) { this.center(); if (!alreadySubscribed(this.beforeShowEvent, this.center)) { this.beforeShowEvent.subscribe(this.center); } if (!alreadySubscribed(windowResizeEvent, this.doCenterOnDOMEvent, this)) { windowResizeEvent.subscribe(this.doCenterOnDOMEvent, this, true); } if (!alreadySubscribed(windowScrollEvent, this.doCenterOnDOMEvent, this)) { windowScrollEvent.subscribe(this.doCenterOnDOMEvent, this, true); } } else { this.beforeShowEvent.unsubscribe(this.center); windowResizeEvent.unsubscribe(this.doCenterOnDOMEvent, this); windowScrollEvent.unsubscribe(this.doCenterOnDOMEvent, this); } }, /** * The default event handler fired when the "height" property is changed. * @method configHeight * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configHeight: function (type, args, obj) { var height = args[0], el = this.element; Dom.setStyle(el, "height", height); this.cfg.refireEvent("iframe"); }, /** * The default event handler fired when the "autofillheight" property is changed. * @method configAutoFillHeight * * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configAutoFillHeight: function (type, args, obj) { var fillEl = args[0], cfg = this.cfg, autoFillHeight = "autofillheight", height = "height", currEl = cfg.getProperty(autoFillHeight), autoFill = this._autoFillOnHeightChange; cfg.unsubscribeFromConfigEvent(height, autoFill); Module.textResizeEvent.unsubscribe(autoFill); this.changeContentEvent.unsubscribe(autoFill); if (currEl && fillEl !== currEl && this[currEl]) { Dom.setStyle(this[currEl], height, ""); } if (fillEl) { fillEl = Lang.trim(fillEl.toLowerCase()); cfg.subscribeToConfigEvent(height, autoFill, this[fillEl], this); Module.textResizeEvent.subscribe(autoFill, this[fillEl], this); this.changeContentEvent.subscribe(autoFill, this[fillEl], this); cfg.setProperty(autoFillHeight, fillEl, true); } }, /** * The default event handler fired when the "width" property is changed. * @method configWidth * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configWidth: function (type, args, obj) { var width = args[0], el = this.element; Dom.setStyle(el, "width", width); this.cfg.refireEvent("iframe"); }, /** * The default event handler fired when the "zIndex" property is changed. * @method configzIndex * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configzIndex: function (type, args, obj) { var zIndex = args[0], el = this.element; if (! zIndex) { zIndex = Dom.getStyle(el, "zIndex"); if (! zIndex || isNaN(zIndex)) { zIndex = 0; } } if (this.iframe || this.cfg.getProperty("iframe") === true) { if (zIndex <= 0) { zIndex = 1; } } Dom.setStyle(el, "zIndex", zIndex); this.cfg.setProperty("zIndex", zIndex, true); if (this.iframe) { this.stackIframe(); } }, /** * The default event handler fired when the "xy" property is changed. * @method configXY * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configXY: function (type, args, obj) { var pos = args[0], x = pos[0], y = pos[1]; this.cfg.setProperty("x", x); this.cfg.setProperty("y", y); this.beforeMoveEvent.fire([x, y]); x = this.cfg.getProperty("x"); y = this.cfg.getProperty("y"); YAHOO.log(("xy: " + [x, y]), "iframe"); this.cfg.refireEvent("iframe"); this.moveEvent.fire([x, y]); }, /** * The default event handler fired when the "x" property is changed. * @method configX * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configX: function (type, args, obj) { var x = args[0], y = this.cfg.getProperty("y"); this.cfg.setProperty("x", x, true); this.cfg.setProperty("y", y, true); this.beforeMoveEvent.fire([x, y]); x = this.cfg.getProperty("x"); y = this.cfg.getProperty("y"); Dom.setX(this.element, x, true); this.cfg.setProperty("xy", [x, y], true); this.cfg.refireEvent("iframe"); this.moveEvent.fire([x, y]); }, /** * The default event handler fired when the "y" property is changed. * @method configY * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configY: function (type, args, obj) { var x = this.cfg.getProperty("x"), y = args[0]; this.cfg.setProperty("x", x, true); this.cfg.setProperty("y", y, true); this.beforeMoveEvent.fire([x, y]); x = this.cfg.getProperty("x"); y = this.cfg.getProperty("y"); Dom.setY(this.element, y, true); this.cfg.setProperty("xy", [x, y], true); this.cfg.refireEvent("iframe"); this.moveEvent.fire([x, y]); }, /** * Shows the iframe shim, if it has been enabled. * @method showIframe */ showIframe: function () { var oIFrame = this.iframe, oParentNode; if (oIFrame) { oParentNode = this.element.parentNode; if (oParentNode != oIFrame.parentNode) { this._addToParent(oParentNode, oIFrame); } oIFrame.style.display = "block"; } }, /** * Hides the iframe shim, if it has been enabled. * @method hideIframe */ hideIframe: function () { if (this.iframe) { this.iframe.style.display = "none"; } }, /** * Syncronizes the size and position of iframe shim to that of its * corresponding Overlay instance. * @method syncIframe */ syncIframe: function () { var oIFrame = this.iframe, oElement = this.element, nOffset = Overlay.IFRAME_OFFSET, nDimensionOffset = (nOffset * 2), aXY; if (oIFrame) { // Size <iframe> oIFrame.style.width = (oElement.offsetWidth + nDimensionOffset + "px"); oIFrame.style.height = (oElement.offsetHeight + nDimensionOffset + "px"); // Position <iframe> aXY = this.cfg.getProperty("xy"); if (!Lang.isArray(aXY) || (isNaN(aXY[0]) || isNaN(aXY[1]))) { this.syncPosition(); aXY = this.cfg.getProperty("xy"); } Dom.setXY(oIFrame, [(aXY[0] - nOffset), (aXY[1] - nOffset)]); } }, /** * Sets the zindex of the iframe shim, if it exists, based on the zindex of * the Overlay element. The zindex of the iframe is set to be one less * than the Overlay element's zindex. * * <p>NOTE: This method will not bump up the zindex of the Overlay element * to ensure that the iframe shim has a non-negative zindex. * If you require the iframe zindex to be 0 or higher, the zindex of * the Overlay element should be set to a value greater than 0, before * this method is called. * </p> * @method stackIframe */ stackIframe: function () { if (this.iframe) { var overlayZ = Dom.getStyle(this.element, "zIndex"); if (!YAHOO.lang.isUndefined(overlayZ) && !isNaN(overlayZ)) { Dom.setStyle(this.iframe, "zIndex", (overlayZ - 1)); } } }, /** * The default event handler fired when the "iframe" property is changed. * @method configIframe * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configIframe: function (type, args, obj) { var bIFrame = args[0]; function createIFrame() { var oIFrame = this.iframe, oElement = this.element, oParent; if (!oIFrame) { if (!m_oIFrameTemplate) { m_oIFrameTemplate = document.createElement("iframe"); if (this.isSecure) { m_oIFrameTemplate.src = Overlay.IFRAME_SRC; } /* Set the opacity of the <iframe> to 0 so that it doesn't modify the opacity of any transparent elements that may be on top of it (like a shadow). */ if (UA.ie) { m_oIFrameTemplate.style.filter = "alpha(opacity=0)"; /* Need to set the "frameBorder" property to 0 supress the default <iframe> border in IE. Setting the CSS "border" property alone doesn't supress it. */ m_oIFrameTemplate.frameBorder = 0; } else { m_oIFrameTemplate.style.opacity = "0"; } m_oIFrameTemplate.style.position = "absolute"; m_oIFrameTemplate.style.border = "none"; m_oIFrameTemplate.style.margin = "0"; m_oIFrameTemplate.style.padding = "0"; m_oIFrameTemplate.style.display = "none"; m_oIFrameTemplate.tabIndex = -1; m_oIFrameTemplate.className = Overlay.CSS_IFRAME; } oIFrame = m_oIFrameTemplate.cloneNode(false); oIFrame.id = this.id + "_f"; oParent = oElement.parentNode; var parentNode = oParent || document.body; this._addToParent(parentNode, oIFrame); this.iframe = oIFrame; } /* Show the <iframe> before positioning it since the "setXY" method of DOM requires the element be in the document and visible. */ this.showIframe(); /* Syncronize the size and position of the <iframe> to that of the Overlay. */ this.syncIframe(); this.stackIframe(); // Add event listeners to update the <iframe> when necessary if (!this._hasIframeEventListeners) { this.showEvent.subscribe(this.showIframe); this.hideEvent.subscribe(this.hideIframe); this.changeContentEvent.subscribe(this.syncIframe); this._hasIframeEventListeners = true; } } function onBeforeShow() { createIFrame.call(this); this.beforeShowEvent.unsubscribe(onBeforeShow); this._iframeDeferred = false; } if (bIFrame) { // <iframe> shim is enabled if (this.cfg.getProperty("visible")) { createIFrame.call(this); } else { if (!this._iframeDeferred) { this.beforeShowEvent.subscribe(onBeforeShow); this._iframeDeferred = true; } } } else { // <iframe> shim is disabled this.hideIframe(); if (this._hasIframeEventListeners) { this.showEvent.unsubscribe(this.showIframe); this.hideEvent.unsubscribe(this.hideIframe); this.changeContentEvent.unsubscribe(this.syncIframe); this._hasIframeEventListeners = false; } } }, /** * Set's the container's XY value from DOM if not already set. * * Differs from syncPosition, in that the XY value is only sync'd with DOM if * not already set. The method also refire's the XY config property event, so any * beforeMove, Move event listeners are invoked. * * @method _primeXYFromDOM * @protected */ _primeXYFromDOM : function() { if (YAHOO.lang.isUndefined(this.cfg.getProperty("xy"))) { // Set CFG XY based on DOM XY this.syncPosition(); // Account for XY being set silently in syncPosition (no moveTo fired/called) this.cfg.refireEvent("xy"); this.beforeShowEvent.unsubscribe(this._primeXYFromDOM); } }, /** * The default event handler fired when the "constraintoviewport" * property is changed. * @method configConstrainToViewport * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for * the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configConstrainToViewport: function (type, args, obj) { var val = args[0]; if (val) { if (! Config.alreadySubscribed(this.beforeMoveEvent, this.enforceConstraints, this)) { this.beforeMoveEvent.subscribe(this.enforceConstraints, this, true); } if (! Config.alreadySubscribed(this.beforeShowEvent, this._primeXYFromDOM)) { this.beforeShowEvent.subscribe(this._primeXYFromDOM); } } else { this.beforeShowEvent.unsubscribe(this._primeXYFromDOM); this.beforeMoveEvent.unsubscribe(this.enforceConstraints, this); } }, /** * The default event handler fired when the "context" property * is changed. * * @method configContext * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configContext: function (type, args, obj) { var contextArgs = args[0], contextEl, elementMagnetCorner, contextMagnetCorner, triggers, offset, defTriggers = this.CONTEXT_TRIGGERS; if (contextArgs) { contextEl = contextArgs[0]; elementMagnetCorner = contextArgs[1]; contextMagnetCorner = contextArgs[2]; triggers = contextArgs[3]; offset = contextArgs[4]; if (defTriggers && defTriggers.length > 0) { triggers = (triggers || []).concat(defTriggers); } if (contextEl) { if (typeof contextEl == "string") { this.cfg.setProperty("context", [ document.getElementById(contextEl), elementMagnetCorner, contextMagnetCorner, triggers, offset], true); } if (elementMagnetCorner && contextMagnetCorner) { this.align(elementMagnetCorner, contextMagnetCorner, offset); } if (this._contextTriggers) { // Unsubscribe Old Set this._processTriggers(this._contextTriggers, _UNSUBSCRIBE, this._alignOnTrigger); } if (triggers) { // Subscribe New Set this._processTriggers(triggers, _SUBSCRIBE, this._alignOnTrigger); this._contextTriggers = triggers; } } } }, /** * Custom Event handler for context alignment triggers. Invokes the align method * * @method _alignOnTrigger * @protected * * @param {String} type The event type (not used by the default implementation) * @param {Any[]} args The array of arguments for the trigger event (not used by the default implementation) */ _alignOnTrigger: function(type, args) { this.align(); }, /** * Helper method to locate the custom event instance for the event name string * passed in. As a convenience measure, any custom events passed in are returned. * * @method _findTriggerCE * @private * * @param {String|CustomEvent} t Either a CustomEvent, or event type (e.g. "windowScroll") for which a * custom event instance needs to be looked up from the Overlay._TRIGGER_MAP. */ _findTriggerCE : function(t) { var tce = null; if (t instanceof CustomEvent) { tce = t; } else if (Overlay._TRIGGER_MAP[t]) { tce = Overlay._TRIGGER_MAP[t]; } return tce; }, /** * Utility method that subscribes or unsubscribes the given * function from the list of trigger events provided. * * @method _processTriggers * @protected * * @param {Array[String|CustomEvent]} triggers An array of either CustomEvents, event type strings * (e.g. "beforeShow", "windowScroll") to/from which the provided function should be * subscribed/unsubscribed respectively. * * @param {String} mode Either "subscribe" or "unsubscribe", specifying whether or not * we are subscribing or unsubscribing trigger listeners * * @param {Function} fn The function to be subscribed/unsubscribed to/from the trigger event. * Context is always set to the overlay instance, and no additional object argument * get passed to the subscribed function. */ _processTriggers : function(triggers, mode, fn) { var t, tce; for (var i = 0, l = triggers.length; i < l; ++i) { t = triggers[i]; tce = this._findTriggerCE(t); if (tce) { tce[mode](fn, this, true); } else { this[mode](t, fn); } } }, // END BUILT-IN PROPERTY EVENT HANDLERS // /** * Aligns the Overlay to its context element using the specified corner * points (represented by the constants TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, * and BOTTOM_RIGHT. * @method align * @param {String} elementAlign The String representing the corner of * the Overlay that should be aligned to the context element * @param {String} contextAlign The corner of the context element * that the elementAlign corner should stick to. * @param {Number[]} xyOffset Optional. A 2 element array specifying the x and y pixel offsets which should be applied * after aligning the element and context corners. For example, passing in [5, -10] for this value, would offset the * Overlay by 5 pixels along the X axis (horizontally) and -10 pixels along the Y axis (vertically) after aligning the specified corners. */ align: function (elementAlign, contextAlign, xyOffset) { var contextArgs = this.cfg.getProperty("context"), me = this, context, element, contextRegion; function doAlign(v, h) { var alignX = null, alignY = null; switch (elementAlign) { case Overlay.TOP_LEFT: alignX = h; alignY = v; break; case Overlay.TOP_RIGHT: alignX = h - element.offsetWidth; alignY = v; break; case Overlay.BOTTOM_LEFT: alignX = h; alignY = v - element.offsetHeight; break; case Overlay.BOTTOM_RIGHT: alignX = h - element.offsetWidth; alignY = v - element.offsetHeight; break; } if (alignX !== null && alignY !== null) { if (xyOffset) { alignX += xyOffset[0]; alignY += xyOffset[1]; } me.moveTo(alignX, alignY); } } if (contextArgs) { context = contextArgs[0]; element = this.element; me = this; if (! elementAlign) { elementAlign = contextArgs[1]; } if (! contextAlign) { contextAlign = contextArgs[2]; } if (!xyOffset && contextArgs[4]) { xyOffset = contextArgs[4]; } if (element && context) { contextRegion = Dom.getRegion(context); switch (contextAlign) { case Overlay.TOP_LEFT: doAlign(contextRegion.top, contextRegion.left); break; case Overlay.TOP_RIGHT: doAlign(contextRegion.top, contextRegion.right); break; case Overlay.BOTTOM_LEFT: doAlign(contextRegion.bottom, contextRegion.left); break; case Overlay.BOTTOM_RIGHT: doAlign(contextRegion.bottom, contextRegion.right); break; } } } }, /** * The default event handler executed when the moveEvent is fired, if the * "constraintoviewport" is set to true. * @method enforceConstraints * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ enforceConstraints: function (type, args, obj) { var pos = args[0]; var cXY = this.getConstrainedXY(pos[0], pos[1]); this.cfg.setProperty("x", cXY[0], true); this.cfg.setProperty("y", cXY[1], true); this.cfg.setProperty("xy", cXY, true); }, /** * Shared implementation method for getConstrainedX and getConstrainedY. * * <p> * Given a coordinate value, returns the calculated coordinate required to * position the Overlay if it is to be constrained to the viewport, based on the * current element size, viewport dimensions, scroll values and preventoverlap * settings * </p> * * @method _getConstrainedPos * @protected * @param {String} pos The coordinate which needs to be constrained, either "x" or "y" * @param {Number} The coordinate value which needs to be constrained * @return {Number} The constrained coordinate value */ _getConstrainedPos: function(pos, val) { var overlayEl = this.element, buffer = Overlay.VIEWPORT_OFFSET, x = (pos == "x"), overlaySize = (x) ? overlayEl.offsetWidth : overlayEl.offsetHeight, viewportSize = (x) ? Dom.getViewportWidth() : Dom.getViewportHeight(), docScroll = (x) ? Dom.getDocumentScrollLeft() : Dom.getDocumentScrollTop(), overlapPositions = (x) ? Overlay.PREVENT_OVERLAP_X : Overlay.PREVENT_OVERLAP_Y, context = this.cfg.getProperty("context"), bOverlayFitsInViewport = (overlaySize + buffer < viewportSize), bPreventContextOverlap = this.cfg.getProperty("preventcontextoverlap") && context && overlapPositions[(context[1] + context[2])], minConstraint = docScroll + buffer, maxConstraint = docScroll + viewportSize - overlaySize - buffer, constrainedVal = val; if (val < minConstraint || val > maxConstraint) { if (bPreventContextOverlap) { constrainedVal = this._preventOverlap(pos, context[0], overlaySize, viewportSize, docScroll); } else { if (bOverlayFitsInViewport) { if (val < minConstraint) { constrainedVal = minConstraint; } else if (val > maxConstraint) { constrainedVal = maxConstraint; } } else { constrainedVal = minConstraint; } } } return constrainedVal; }, /** * Helper method, used to position the Overlap to prevent overlap with the * context element (used when preventcontextoverlap is enabled) * * @method _preventOverlap * @protected * @param {String} pos The coordinate to prevent overlap for, either "x" or "y". * @param {HTMLElement} contextEl The context element * @param {Number} overlaySize The related overlay dimension value (for "x", the width, for "y", the height) * @param {Number} viewportSize The related viewport dimension value (for "x", the width, for "y", the height) * @param {Object} docScroll The related document scroll value (for "x", the scrollLeft, for "y", the scrollTop) * * @return {Number} The new coordinate value which was set to prevent overlap */ _preventOverlap : function(pos, contextEl, overlaySize, viewportSize, docScroll) { var x = (pos == "x"), buffer = Overlay.VIEWPORT_OFFSET, overlay = this, contextElPos = ((x) ? Dom.getX(contextEl) : Dom.getY(contextEl)) - docScroll, contextElSize = (x) ? contextEl.offsetWidth : contextEl.offsetHeight, minRegionSize = contextElPos - buffer, maxRegionSize = (viewportSize - (contextElPos + contextElSize)) - buffer, bFlipped = false, flip = function () { var flippedVal; if ((overlay.cfg.getProperty(pos) - docScroll) > contextElPos) { flippedVal = (contextElPos - overlaySize); } else { flippedVal = (contextElPos + contextElSize); } overlay.cfg.setProperty(pos, (flippedVal + docScroll), true); return flippedVal; }, setPosition = function () { var displayRegionSize = ((overlay.cfg.getProperty(pos) - docScroll) > contextElPos) ? maxRegionSize : minRegionSize, position; if (overlaySize > displayRegionSize) { if (bFlipped) { /* All possible positions and values have been tried, but none were successful, so fall back to the original size and position. */ flip(); } else { flip(); bFlipped = true; position = setPosition(); } } return position; }; setPosition(); return this.cfg.getProperty(pos); }, /** * Given x coordinate value, returns the calculated x coordinate required to * position the Overlay if it is to be constrained to the viewport, based on the * current element size, viewport dimensions and scroll values. * * @param {Number} x The X coordinate value to be constrained * @return {Number} The constrained x coordinate */ getConstrainedX: function (x) { return this._getConstrainedPos("x", x); }, /** * Given y coordinate value, returns the calculated y coordinate required to * position the Overlay if it is to be constrained to the viewport, based on the * current element size, viewport dimensions and scroll values. * * @param {Number} y The Y coordinate value to be constrained * @return {Number} The constrained y coordinate */ getConstrainedY : function (y) { return this._getConstrainedPos("y", y); }, /** * Given x, y coordinate values, returns the calculated coordinates required to * position the Overlay if it is to be constrained to the viewport, based on the * current element size, viewport dimensions and scroll values. * * @param {Number} x The X coordinate value to be constrained * @param {Number} y The Y coordinate value to be constrained * @return {Array} The constrained x and y coordinates at index 0 and 1 respectively; */ getConstrainedXY: function(x, y) { return [this.getConstrainedX(x), this.getConstrainedY(y)]; }, /** * Centers the container in the viewport. * @method center */ center: function () { var nViewportOffset = Overlay.VIEWPORT_OFFSET, elementWidth = this.element.offsetWidth, elementHeight = this.element.offsetHeight, viewPortWidth = Dom.getViewportWidth(), viewPortHeight = Dom.getViewportHeight(), x, y; if (elementWidth < viewPortWidth) { x = (viewPortWidth / 2) - (elementWidth / 2) + Dom.getDocumentScrollLeft(); } else { x = nViewportOffset + Dom.getDocumentScrollLeft(); } if (elementHeight < viewPortHeight) { y = (viewPortHeight / 2) - (elementHeight / 2) + Dom.getDocumentScrollTop(); } else { y = nViewportOffset + Dom.getDocumentScrollTop(); } this.cfg.setProperty("xy", [parseInt(x, 10), parseInt(y, 10)]); this.cfg.refireEvent("iframe"); if (UA.webkit) { this.forceContainerRedraw(); } }, /** * Synchronizes the Panel's "xy", "x", and "y" properties with the * Panel's position in the DOM. This is primarily used to update * position information during drag & drop. * @method syncPosition */ syncPosition: function () { var pos = Dom.getXY(this.element); this.cfg.setProperty("x", pos[0], true); this.cfg.setProperty("y", pos[1], true); this.cfg.setProperty("xy", pos, true); }, /** * Event handler fired when the resize monitor element is resized. * @method onDomResize * @param {DOMEvent} e The resize DOM event * @param {Object} obj The scope object */ onDomResize: function (e, obj) { var me = this; Overlay.superclass.onDomResize.call(this, e, obj); setTimeout(function () { me.syncPosition(); me.cfg.refireEvent("iframe"); me.cfg.refireEvent("context"); }, 0); }, /** * Determines the content box height of the given element (height of the element, without padding or borders) in pixels. * * @method _getComputedHeight * @private * @param {HTMLElement} el The element for which the content height needs to be determined * @return {Number} The content box height of the given element, or null if it could not be determined. */ _getComputedHeight : (function() { if (document.defaultView && document.defaultView.getComputedStyle) { return function(el) { var height = null; if (el.ownerDocument && el.ownerDocument.defaultView) { var computed = el.ownerDocument.defaultView.getComputedStyle(el, ''); if (computed) { height = parseInt(computed.height, 10); } } return (Lang.isNumber(height)) ? height : null; }; } else { return function(el) { var height = null; if (el.style.pixelHeight) { height = el.style.pixelHeight; } return (Lang.isNumber(height)) ? height : null; }; } })(), /** * autofillheight validator. Verifies that the autofill value is either null * or one of the strings : "body", "header" or "footer". * * @method _validateAutoFillHeight * @protected * @param {String} val * @return true, if valid, false otherwise */ _validateAutoFillHeight : function(val) { return (!val) || (Lang.isString(val) && Overlay.STD_MOD_RE.test(val)); }, /** * The default custom event handler executed when the overlay's height is changed, * if the autofillheight property has been set. * * @method _autoFillOnHeightChange * @protected * @param {String} type The event type * @param {Array} args The array of arguments passed to event subscribers * @param {HTMLElement} el The header, body or footer element which is to be resized to fill * out the containers height */ _autoFillOnHeightChange : function(type, args, el) { var height = this.cfg.getProperty("height"); if ((height && height !== "auto") || (height === 0)) { this.fillHeight(el); } }, /** * Returns the sub-pixel height of the el, using getBoundingClientRect, if available, * otherwise returns the offsetHeight * @method _getPreciseHeight * @private * @param {HTMLElement} el * @return {Float} The sub-pixel height if supported by the browser, else the rounded height. */ _getPreciseHeight : function(el) { var height = el.offsetHeight; if (el.getBoundingClientRect) { var rect = el.getBoundingClientRect(); height = rect.bottom - rect.top; } return height; }, /** * <p> * Sets the height on the provided header, body or footer element to * fill out the height of the container. It determines the height of the * containers content box, based on it's configured height value, and * sets the height of the autofillheight element to fill out any * space remaining after the other standard module element heights * have been accounted for. * </p> * <p><strong>NOTE:</strong> This method is not designed to work if an explicit * height has not been set on the container, since for an "auto" height container, * the heights of the header/body/footer will drive the height of the container.</p> * * @method fillHeight * @param {HTMLElement} el The element which should be resized to fill out the height * of the container element. */ fillHeight : function(el) { if (el) { var container = this.innerElement || this.element, containerEls = [this.header, this.body, this.footer], containerEl, total = 0, filled = 0, remaining = 0, validEl = false; for (var i = 0, l = containerEls.length; i < l; i++) { containerEl = containerEls[i]; if (containerEl) { if (el !== containerEl) { filled += this._getPreciseHeight(containerEl); } else { validEl = true; } } } if (validEl) { if (UA.ie || UA.opera) { // Need to set height to 0, to allow height to be reduced Dom.setStyle(el, 'height', 0 + 'px'); } total = this._getComputedHeight(container); // Fallback, if we can't get computed value for content height if (total === null) { Dom.addClass(container, "yui-override-padding"); total = container.clientHeight; // Content, No Border, 0 Padding (set by yui-override-padding) Dom.removeClass(container, "yui-override-padding"); } remaining = Math.max(total - filled, 0); Dom.setStyle(el, "height", remaining + "px"); // Re-adjust height if required, to account for el padding and border if (el.offsetHeight != remaining) { remaining = Math.max(remaining - (el.offsetHeight - remaining), 0); } Dom.setStyle(el, "height", remaining + "px"); } } }, /** * Places the Overlay on top of all other instances of * YAHOO.widget.Overlay. * @method bringToTop */ bringToTop: function () { var aOverlays = [], oElement = this.element; function compareZIndexDesc(p_oOverlay1, p_oOverlay2) { var sZIndex1 = Dom.getStyle(p_oOverlay1, "zIndex"), sZIndex2 = Dom.getStyle(p_oOverlay2, "zIndex"), nZIndex1 = (!sZIndex1 || isNaN(sZIndex1)) ? 0 : parseInt(sZIndex1, 10), nZIndex2 = (!sZIndex2 || isNaN(sZIndex2)) ? 0 : parseInt(sZIndex2, 10); if (nZIndex1 > nZIndex2) { return -1; } else if (nZIndex1 < nZIndex2) { return 1; } else { return 0; } } function isOverlayElement(p_oElement) { var isOverlay = Dom.hasClass(p_oElement, Overlay.CSS_OVERLAY), Panel = YAHOO.widget.Panel; if (isOverlay && !Dom.isAncestor(oElement, p_oElement)) { if (Panel && Dom.hasClass(p_oElement, Panel.CSS_PANEL)) { aOverlays[aOverlays.length] = p_oElement.parentNode; } else { aOverlays[aOverlays.length] = p_oElement; } } } Dom.getElementsBy(isOverlayElement, "div", document.body); aOverlays.sort(compareZIndexDesc); var oTopOverlay = aOverlays[0], nTopZIndex; if (oTopOverlay) { nTopZIndex = Dom.getStyle(oTopOverlay, "zIndex"); if (!isNaN(nTopZIndex)) { var bRequiresBump = false; if (oTopOverlay != oElement) { bRequiresBump = true; } else if (aOverlays.length > 1) { var nNextZIndex = Dom.getStyle(aOverlays[1], "zIndex"); // Don't rely on DOM order to stack if 2 overlays are at the same zindex. if (!isNaN(nNextZIndex) && (nTopZIndex == nNextZIndex)) { bRequiresBump = true; } } if (bRequiresBump) { this.cfg.setProperty("zindex", (parseInt(nTopZIndex, 10) + 2)); } } } }, /** * Removes the Overlay element from the DOM and sets all child * elements to null. * @method destroy * @param {boolean} shallowPurge If true, only the parent element's DOM event listeners are purged. If false, or not provided, all children are also purged of DOM event listeners. * NOTE: The flag is a "shallowPurge" flag, as opposed to what may be a more intuitive "purgeChildren" flag to maintain backwards compatibility with behavior prior to 2.9.0. */ destroy: function (shallowPurge) { if (this.iframe) { this.iframe.parentNode.removeChild(this.iframe); } this.iframe = null; Overlay.windowResizeEvent.unsubscribe( this.doCenterOnDOMEvent, this); Overlay.windowScrollEvent.unsubscribe( this.doCenterOnDOMEvent, this); Module.textResizeEvent.unsubscribe(this._autoFillOnHeightChange); if (this._contextTriggers) { // Unsubscribe context triggers - to cover context triggers which listen for global // events such as windowResize and windowScroll. Easier just to unsubscribe all this._processTriggers(this._contextTriggers, _UNSUBSCRIBE, this._alignOnTrigger); } Overlay.superclass.destroy.call(this, shallowPurge); }, /** * Can be used to force the container to repaint/redraw it's contents. * <p> * By default applies and then removes a 1px bottom margin through the * application/removal of a "yui-force-redraw" class. * </p> * <p> * It is currently used by Overlay to force a repaint for webkit * browsers, when centering. * </p> * @method forceContainerRedraw */ forceContainerRedraw : function() { var c = this; Dom.addClass(c.element, "yui-force-redraw"); setTimeout(function() { Dom.removeClass(c.element, "yui-force-redraw"); }, 0); }, /** * Returns a String representation of the object. * @method toString * @return {String} The string representation of the Overlay. */ toString: function () { return "Overlay " + this.id; } }); }()); (function () { /** * OverlayManager is used for maintaining the focus status of * multiple Overlays. * @namespace YAHOO.widget * @namespace YAHOO.widget * @class OverlayManager * @constructor * @param {Array} overlays Optional. A collection of Overlays to register * with the manager. * @param {Object} userConfig The object literal representing the user * configuration of the OverlayManager */ YAHOO.widget.OverlayManager = function (userConfig) { this.init(userConfig); }; var Overlay = YAHOO.widget.Overlay, Event = YAHOO.util.Event, Dom = YAHOO.util.Dom, Config = YAHOO.util.Config, CustomEvent = YAHOO.util.CustomEvent, OverlayManager = YAHOO.widget.OverlayManager; /** * The CSS class representing a focused Overlay * @property OverlayManager.CSS_FOCUSED * @static * @final * @type String */ OverlayManager.CSS_FOCUSED = "focused"; OverlayManager.prototype = { /** * The class's constructor function * @property contructor * @type Function */ constructor: OverlayManager, /** * The array of Overlays that are currently registered * @property overlays * @type YAHOO.widget.Overlay[] */ overlays: null, /** * Initializes the default configuration of the OverlayManager * @method initDefaultConfig */ initDefaultConfig: function () { /** * The collection of registered Overlays in use by * the OverlayManager * @config overlays * @type YAHOO.widget.Overlay[] * @default null */ this.cfg.addProperty("overlays", { suppressEvent: true } ); /** * The default DOM event that should be used to focus an Overlay * @config focusevent * @type String * @default "mousedown" */ this.cfg.addProperty("focusevent", { value: "mousedown" } ); }, /** * Initializes the OverlayManager * @method init * @param {Overlay[]} overlays Optional. A collection of Overlays to * register with the manager. * @param {Object} userConfig The object literal representing the user * configuration of the OverlayManager */ init: function (userConfig) { /** * The OverlayManager's Config object used for monitoring * configuration properties. * @property cfg * @type Config */ this.cfg = new Config(this); this.initDefaultConfig(); if (userConfig) { this.cfg.applyConfig(userConfig, true); } this.cfg.fireQueue(); /** * The currently activated Overlay * @property activeOverlay * @private * @type YAHOO.widget.Overlay */ var activeOverlay = null; /** * Returns the currently focused Overlay * @method getActive * @return {Overlay} The currently focused Overlay */ this.getActive = function () { return activeOverlay; }; /** * Focuses the specified Overlay * @method focus * @param {Overlay} overlay The Overlay to focus * @param {String} overlay The id of the Overlay to focus */ this.focus = function (overlay) { var o = this.find(overlay); if (o) { o.focus(); } }; /** * Removes the specified Overlay from the manager * @method remove * @param {Overlay} overlay The Overlay to remove * @param {String} overlay The id of the Overlay to remove */ this.remove = function (overlay) { var o = this.find(overlay), originalZ; if (o) { if (activeOverlay == o) { activeOverlay = null; } var bDestroyed = (o.element === null && o.cfg === null) ? true : false; if (!bDestroyed) { // Set it's zindex so that it's sorted to the end. originalZ = Dom.getStyle(o.element, "zIndex"); o.cfg.setProperty("zIndex", -1000, true); } this.overlays.sort(this.compareZIndexDesc); this.overlays = this.overlays.slice(0, (this.overlays.length - 1)); o.hideEvent.unsubscribe(o.blur); o.destroyEvent.unsubscribe(this._onOverlayDestroy, o); o.focusEvent.unsubscribe(this._onOverlayFocusHandler, o); o.blurEvent.unsubscribe(this._onOverlayBlurHandler, o); if (!bDestroyed) { Event.removeListener(o.element, this.cfg.getProperty("focusevent"), this._onOverlayElementFocus); o.cfg.setProperty("zIndex", originalZ, true); o.cfg.setProperty("manager", null); } /* _managed Flag for custom or existing. Don't want to remove existing */ if (o.focusEvent._managed) { o.focusEvent = null; } if (o.blurEvent._managed) { o.blurEvent = null; } if (o.focus._managed) { o.focus = null; } if (o.blur._managed) { o.blur = null; } } }; /** * Removes focus from all registered Overlays in the manager * @method blurAll */ this.blurAll = function () { var nOverlays = this.overlays.length, i; if (nOverlays > 0) { i = nOverlays - 1; do { this.overlays[i].blur(); } while(i--); } }; /** * Updates the state of the OverlayManager and overlay, as a result of the overlay * being blurred. * * @method _manageBlur * @param {Overlay} overlay The overlay instance which got blurred. * @protected */ this._manageBlur = function (overlay) { var changed = false; if (activeOverlay == overlay) { Dom.removeClass(activeOverlay.element, OverlayManager.CSS_FOCUSED); activeOverlay = null; changed = true; } return changed; }; /** * Updates the state of the OverlayManager and overlay, as a result of the overlay * receiving focus. * * @method _manageFocus * @param {Overlay} overlay The overlay instance which got focus. * @protected */ this._manageFocus = function(overlay) { var changed = false; if (activeOverlay != overlay) { if (activeOverlay) { activeOverlay.blur(); } activeOverlay = overlay; this.bringToTop(activeOverlay); Dom.addClass(activeOverlay.element, OverlayManager.CSS_FOCUSED); changed = true; } return changed; }; var overlays = this.cfg.getProperty("overlays"); if (! this.overlays) { this.overlays = []; } if (overlays) { this.register(overlays); this.overlays.sort(this.compareZIndexDesc); } }, /** * @method _onOverlayElementFocus * @description Event handler for the DOM event that is used to focus * the Overlay instance as specified by the "focusevent" * configuration property. * @private * @param {Event} p_oEvent Object representing the DOM event * object passed back by the event utility (Event). */ _onOverlayElementFocus: function (p_oEvent) { var oTarget = Event.getTarget(p_oEvent), oClose = this.close; if (oClose && (oTarget == oClose || Dom.isAncestor(oClose, oTarget))) { this.blur(); } else { this.focus(); } }, /** * @method _onOverlayDestroy * @description "destroy" event handler for the Overlay. * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. * @param {Overlay} p_oOverlay Object representing the overlay that * fired the event. */ _onOverlayDestroy: function (p_sType, p_aArgs, p_oOverlay) { this.remove(p_oOverlay); }, /** * @method _onOverlayFocusHandler * * @description focusEvent Handler, used to delegate to _manageFocus with the correct arguments. * * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. * @param {Overlay} p_oOverlay Object representing the overlay that * fired the event. */ _onOverlayFocusHandler: function(p_sType, p_aArgs, p_oOverlay) { this._manageFocus(p_oOverlay); }, /** * @method _onOverlayBlurHandler * @description blurEvent Handler, used to delegate to _manageBlur with the correct arguments. * * @private * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. * @param {Overlay} p_oOverlay Object representing the overlay that * fired the event. */ _onOverlayBlurHandler: function(p_sType, p_aArgs, p_oOverlay) { this._manageBlur(p_oOverlay); }, /** * Subscribes to the Overlay based instance focusEvent, to allow the OverlayManager to * monitor focus state. * * If the instance already has a focusEvent (e.g. Menu), OverlayManager will subscribe * to the existing focusEvent, however if a focusEvent or focus method does not exist * on the instance, the _bindFocus method will add them, and the focus method will * update the OverlayManager's state directly. * * @method _bindFocus * @param {Overlay} overlay The overlay for which focus needs to be managed * @protected */ _bindFocus : function(overlay) { var mgr = this; if (!overlay.focusEvent) { overlay.focusEvent = overlay.createEvent("focus"); overlay.focusEvent.signature = CustomEvent.LIST; overlay.focusEvent._managed = true; } else { overlay.focusEvent.subscribe(mgr._onOverlayFocusHandler, overlay, mgr); } if (!overlay.focus) { Event.on(overlay.element, mgr.cfg.getProperty("focusevent"), mgr._onOverlayElementFocus, null, overlay); overlay.focus = function () { if (mgr._manageFocus(this)) { // For Panel/Dialog if (this.cfg.getProperty("visible") && this.focusFirst) { this.focusFirst(); } this.focusEvent.fire(); } }; overlay.focus._managed = true; } }, /** * Subscribes to the Overlay based instance's blurEvent to allow the OverlayManager to * monitor blur state. * * If the instance already has a blurEvent (e.g. Menu), OverlayManager will subscribe * to the existing blurEvent, however if a blurEvent or blur method does not exist * on the instance, the _bindBlur method will add them, and the blur method * update the OverlayManager's state directly. * * @method _bindBlur * @param {Overlay} overlay The overlay for which blur needs to be managed * @protected */ _bindBlur : function(overlay) { var mgr = this; if (!overlay.blurEvent) { overlay.blurEvent = overlay.createEvent("blur"); overlay.blurEvent.signature = CustomEvent.LIST; overlay.focusEvent._managed = true; } else { overlay.blurEvent.subscribe(mgr._onOverlayBlurHandler, overlay, mgr); } if (!overlay.blur) { overlay.blur = function () { if (mgr._manageBlur(this)) { this.blurEvent.fire(); } }; overlay.blur._managed = true; } overlay.hideEvent.subscribe(overlay.blur); }, /** * Subscribes to the Overlay based instance's destroyEvent, to allow the Overlay * to be removed for the OverlayManager when destroyed. * * @method _bindDestroy * @param {Overlay} overlay The overlay instance being managed * @protected */ _bindDestroy : function(overlay) { var mgr = this; overlay.destroyEvent.subscribe(mgr._onOverlayDestroy, overlay, mgr); }, /** * Ensures the zIndex configuration property on the managed overlay based instance * is set to the computed zIndex value from the DOM (with "auto" translating to 0). * * @method _syncZIndex * @param {Overlay} overlay The overlay instance being managed * @protected */ _syncZIndex : function(overlay) { var zIndex = Dom.getStyle(overlay.element, "zIndex"); if (!isNaN(zIndex)) { overlay.cfg.setProperty("zIndex", parseInt(zIndex, 10)); } else { overlay.cfg.setProperty("zIndex", 0); } }, /** * Registers an Overlay or an array of Overlays with the manager. Upon * registration, the Overlay receives functions for focus and blur, * along with CustomEvents for each. * * @method register * @param {Overlay} overlay An Overlay to register with the manager. * @param {Overlay[]} overlay An array of Overlays to register with * the manager. * @return {boolean} true if any Overlays are registered. */ register: function (overlay) { var registered = false, i, n; if (overlay instanceof Overlay) { overlay.cfg.addProperty("manager", { value: this } ); this._bindFocus(overlay); this._bindBlur(overlay); this._bindDestroy(overlay); this._syncZIndex(overlay); this.overlays.push(overlay); this.bringToTop(overlay); registered = true; } else if (overlay instanceof Array) { for (i = 0, n = overlay.length; i < n; i++) { registered = this.register(overlay[i]) || registered; } } return registered; }, /** * Places the specified Overlay instance on top of all other * Overlay instances. * @method bringToTop * @param {YAHOO.widget.Overlay} p_oOverlay Object representing an * Overlay instance. * @param {String} p_oOverlay String representing the id of an * Overlay instance. */ bringToTop: function (p_oOverlay) { var oOverlay = this.find(p_oOverlay), nTopZIndex, oTopOverlay, aOverlays; if (oOverlay) { aOverlays = this.overlays; aOverlays.sort(this.compareZIndexDesc); oTopOverlay = aOverlays[0]; if (oTopOverlay) { nTopZIndex = Dom.getStyle(oTopOverlay.element, "zIndex"); if (!isNaN(nTopZIndex)) { var bRequiresBump = false; if (oTopOverlay !== oOverlay) { bRequiresBump = true; } else if (aOverlays.length > 1) { var nNextZIndex = Dom.getStyle(aOverlays[1].element, "zIndex"); // Don't rely on DOM order to stack if 2 overlays are at the same zindex. if (!isNaN(nNextZIndex) && (nTopZIndex == nNextZIndex)) { bRequiresBump = true; } } if (bRequiresBump) { oOverlay.cfg.setProperty("zindex", (parseInt(nTopZIndex, 10) + 2)); } } aOverlays.sort(this.compareZIndexDesc); } } }, /** * Attempts to locate an Overlay by instance or ID. * @method find * @param {Overlay} overlay An Overlay to locate within the manager * @param {String} overlay An Overlay id to locate within the manager * @return {Overlay} The requested Overlay, if found, or null if it * cannot be located. */ find: function (overlay) { var isInstance = overlay instanceof Overlay, overlays = this.overlays, n = overlays.length, found = null, o, i; if (isInstance || typeof overlay == "string") { for (i = n-1; i >= 0; i--) { o = overlays[i]; if ((isInstance && (o === overlay)) || (o.id == overlay)) { found = o; break; } } } return found; }, /** * Used for sorting the manager's Overlays by z-index. * @method compareZIndexDesc * @private * @return {Number} 0, 1, or -1, depending on where the Overlay should * fall in the stacking order. */ compareZIndexDesc: function (o1, o2) { var zIndex1 = (o1.cfg) ? o1.cfg.getProperty("zIndex") : null, // Sort invalid (destroyed) zIndex2 = (o2.cfg) ? o2.cfg.getProperty("zIndex") : null; // objects at bottom. if (zIndex1 === null && zIndex2 === null) { return 0; } else if (zIndex1 === null){ return 1; } else if (zIndex2 === null) { return -1; } else if (zIndex1 > zIndex2) { return -1; } else if (zIndex1 < zIndex2) { return 1; } else { return 0; } }, /** * Shows all Overlays in the manager. * @method showAll */ showAll: function () { var overlays = this.overlays, n = overlays.length, i; for (i = n - 1; i >= 0; i--) { overlays[i].show(); } }, /** * Hides all Overlays in the manager. * @method hideAll */ hideAll: function () { var overlays = this.overlays, n = overlays.length, i; for (i = n - 1; i >= 0; i--) { overlays[i].hide(); } }, /** * Returns a string representation of the object. * @method toString * @return {String} The string representation of the OverlayManager */ toString: function () { return "OverlayManager"; } }; }()); (function () { /** * Tooltip is an implementation of Overlay that behaves like an OS tooltip, * displaying when the user mouses over a particular element, and * disappearing on mouse out. * @namespace YAHOO.widget * @class Tooltip * @extends YAHOO.widget.Overlay * @constructor * @param {String} el The element ID representing the Tooltip <em>OR</em> * @param {HTMLElement} el The element representing the Tooltip * @param {Object} userConfig The configuration object literal containing * the configuration that should be set for this Overlay. See configuration * documentation for more details. */ YAHOO.widget.Tooltip = function (el, userConfig) { YAHOO.widget.Tooltip.superclass.constructor.call(this, el, userConfig); }; var Lang = YAHOO.lang, Event = YAHOO.util.Event, CustomEvent = YAHOO.util.CustomEvent, Dom = YAHOO.util.Dom, Tooltip = YAHOO.widget.Tooltip, UA = YAHOO.env.ua, bIEQuirks = (UA.ie && (UA.ie <= 6 || document.compatMode == "BackCompat")), m_oShadowTemplate, /** * Constant representing the Tooltip's configuration properties * @property DEFAULT_CONFIG * @private * @final * @type Object */ DEFAULT_CONFIG = { "PREVENT_OVERLAP": { key: "preventoverlap", value: true, validator: Lang.isBoolean, supercedes: ["x", "y", "xy"] }, "SHOW_DELAY": { key: "showdelay", value: 200, validator: Lang.isNumber }, "AUTO_DISMISS_DELAY": { key: "autodismissdelay", value: 5000, validator: Lang.isNumber }, "HIDE_DELAY": { key: "hidedelay", value: 250, validator: Lang.isNumber }, "TEXT": { key: "text", suppressEvent: true }, "CONTAINER": { key: "container" }, "DISABLED": { key: "disabled", value: false, suppressEvent: true }, "XY_OFFSET": { key: "xyoffset", value: [0, 25], suppressEvent: true } }, /** * Constant representing the name of the Tooltip's events * @property EVENT_TYPES * @private * @final * @type Object */ EVENT_TYPES = { "CONTEXT_MOUSE_OVER": "contextMouseOver", "CONTEXT_MOUSE_OUT": "contextMouseOut", "CONTEXT_TRIGGER": "contextTrigger" }; /** * Constant representing the Tooltip CSS class * @property YAHOO.widget.Tooltip.CSS_TOOLTIP * @static * @final * @type String */ Tooltip.CSS_TOOLTIP = "yui-tt"; function restoreOriginalWidth(sOriginalWidth, sForcedWidth) { var oConfig = this.cfg, sCurrentWidth = oConfig.getProperty("width"); if (sCurrentWidth == sForcedWidth) { oConfig.setProperty("width", sOriginalWidth); } } /* changeContent event handler that sets a Tooltip instance's "width" configuration property to the value of its root HTML elements's offsetWidth if a specific width has not been set. */ function setWidthToOffsetWidth(p_sType, p_aArgs) { if ("_originalWidth" in this) { restoreOriginalWidth.call(this, this._originalWidth, this._forcedWidth); } var oBody = document.body, oConfig = this.cfg, sOriginalWidth = oConfig.getProperty("width"), sNewWidth, oClone; if ((!sOriginalWidth || sOriginalWidth == "auto") && (oConfig.getProperty("container") != oBody || oConfig.getProperty("x") >= Dom.getViewportWidth() || oConfig.getProperty("y") >= Dom.getViewportHeight())) { oClone = this.element.cloneNode(true); oClone.style.visibility = "hidden"; oClone.style.top = "0px"; oClone.style.left = "0px"; oBody.appendChild(oClone); sNewWidth = (oClone.offsetWidth + "px"); oBody.removeChild(oClone); oClone = null; oConfig.setProperty("width", sNewWidth); oConfig.refireEvent("xy"); this._originalWidth = sOriginalWidth || ""; this._forcedWidth = sNewWidth; } } // "onDOMReady" that renders the ToolTip function onDOMReady(p_sType, p_aArgs, p_oObject) { this.render(p_oObject); } // "init" event handler that automatically renders the Tooltip function onInit() { Event.onDOMReady(onDOMReady, this.cfg.getProperty("container"), this); } YAHOO.extend(Tooltip, YAHOO.widget.Overlay, { /** * The Tooltip initialization method. This method is automatically * called by the constructor. A Tooltip is automatically rendered by * the init method, and it also is set to be invisible by default, * and constrained to viewport by default as well. * @method init * @param {String} el The element ID representing the Tooltip <em>OR</em> * @param {HTMLElement} el The element representing the Tooltip * @param {Object} userConfig The configuration object literal * containing the configuration that should be set for this Tooltip. * See configuration documentation for more details. */ init: function (el, userConfig) { this.logger = new YAHOO.widget.LogWriter(this.toString()); Tooltip.superclass.init.call(this, el); this.beforeInitEvent.fire(Tooltip); Dom.addClass(this.element, Tooltip.CSS_TOOLTIP); if (userConfig) { this.cfg.applyConfig(userConfig, true); } this.cfg.queueProperty("visible", false); this.cfg.queueProperty("constraintoviewport", true); this.setBody(""); this.subscribe("changeContent", setWidthToOffsetWidth); this.subscribe("init", onInit); this.subscribe("render", this.onRender); this.initEvent.fire(Tooltip); }, /** * Initializes the custom events for Tooltip * @method initEvents */ initEvents: function () { Tooltip.superclass.initEvents.call(this); var SIGNATURE = CustomEvent.LIST; /** * CustomEvent fired when user mouses over a context element. Returning false from * a subscriber to this event will prevent the tooltip from being displayed for * the current context element. * * @event contextMouseOverEvent * @param {HTMLElement} context The context element which the user just moused over * @param {DOMEvent} e The DOM event object, associated with the mouse over */ this.contextMouseOverEvent = this.createEvent(EVENT_TYPES.CONTEXT_MOUSE_OVER); this.contextMouseOverEvent.signature = SIGNATURE; /** * CustomEvent fired when the user mouses out of a context element. * * @event contextMouseOutEvent * @param {HTMLElement} context The context element which the user just moused out of * @param {DOMEvent} e The DOM event object, associated with the mouse out */ this.contextMouseOutEvent = this.createEvent(EVENT_TYPES.CONTEXT_MOUSE_OUT); this.contextMouseOutEvent.signature = SIGNATURE; /** * CustomEvent fired just before the tooltip is displayed for the current context. * <p> * You can subscribe to this event if you need to set up the text for the * tooltip based on the context element for which it is about to be displayed. * </p> * <p>This event differs from the beforeShow event in following respects:</p> * <ol> * <li> * When moving from one context element to another, if the tooltip is not * hidden (the <code>hidedelay</code> is not reached), the beforeShow and Show events will not * be fired when the tooltip is displayed for the new context since it is already visible. * However the contextTrigger event is always fired before displaying the tooltip for * a new context. * </li> * <li> * The trigger event provides access to the context element, allowing you to * set the text of the tooltip based on context element for which the tooltip is * triggered. * </li> * </ol> * <p> * It is not possible to prevent the tooltip from being displayed * using this event. You can use the contextMouseOverEvent if you need to prevent * the tooltip from being displayed. * </p> * @event contextTriggerEvent * @param {HTMLElement} context The context element for which the tooltip is triggered */ this.contextTriggerEvent = this.createEvent(EVENT_TYPES.CONTEXT_TRIGGER); this.contextTriggerEvent.signature = SIGNATURE; }, /** * Initializes the class's configurable properties which can be * changed using the Overlay's Config object (cfg). * @method initDefaultConfig */ initDefaultConfig: function () { Tooltip.superclass.initDefaultConfig.call(this); /** * Specifies whether the Tooltip should be kept from overlapping * its context element. * @config preventoverlap * @type Boolean * @default true */ this.cfg.addProperty(DEFAULT_CONFIG.PREVENT_OVERLAP.key, { value: DEFAULT_CONFIG.PREVENT_OVERLAP.value, validator: DEFAULT_CONFIG.PREVENT_OVERLAP.validator, supercedes: DEFAULT_CONFIG.PREVENT_OVERLAP.supercedes }); /** * The number of milliseconds to wait before showing a Tooltip * on mouseover. * @config showdelay * @type Number * @default 200 */ this.cfg.addProperty(DEFAULT_CONFIG.SHOW_DELAY.key, { handler: this.configShowDelay, value: 200, validator: DEFAULT_CONFIG.SHOW_DELAY.validator }); /** * The number of milliseconds to wait before automatically * dismissing a Tooltip after the mouse has been resting on the * context element. * @config autodismissdelay * @type Number * @default 5000 */ this.cfg.addProperty(DEFAULT_CONFIG.AUTO_DISMISS_DELAY.key, { handler: this.configAutoDismissDelay, value: DEFAULT_CONFIG.AUTO_DISMISS_DELAY.value, validator: DEFAULT_CONFIG.AUTO_DISMISS_DELAY.validator }); /** * The number of milliseconds to wait before hiding a Tooltip * after mouseout. * @config hidedelay * @type Number * @default 250 */ this.cfg.addProperty(DEFAULT_CONFIG.HIDE_DELAY.key, { handler: this.configHideDelay, value: DEFAULT_CONFIG.HIDE_DELAY.value, validator: DEFAULT_CONFIG.HIDE_DELAY.validator }); /** * Specifies the Tooltip's text. The text is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @config text * @type HTML * @default null */ this.cfg.addProperty(DEFAULT_CONFIG.TEXT.key, { handler: this.configText, suppressEvent: DEFAULT_CONFIG.TEXT.suppressEvent }); /** * Specifies the container element that the Tooltip's markup * should be rendered into. * @config container * @type HTMLElement/String * @default document.body */ this.cfg.addProperty(DEFAULT_CONFIG.CONTAINER.key, { handler: this.configContainer, value: document.body }); /** * Specifies whether or not the tooltip is disabled. Disabled tooltips * will not be displayed. If the tooltip is driven by the title attribute * of the context element, the title attribute will still be removed for * disabled tooltips, to prevent default tooltip behavior. * * @config disabled * @type Boolean * @default false */ this.cfg.addProperty(DEFAULT_CONFIG.DISABLED.key, { handler: this.configContainer, value: DEFAULT_CONFIG.DISABLED.value, supressEvent: DEFAULT_CONFIG.DISABLED.suppressEvent }); /** * Specifies the XY offset from the mouse position, where the tooltip should be displayed, specified * as a 2 element array (e.g. [10, 20]); * * @config xyoffset * @type Array * @default [0, 25] */ this.cfg.addProperty(DEFAULT_CONFIG.XY_OFFSET.key, { value: DEFAULT_CONFIG.XY_OFFSET.value.concat(), supressEvent: DEFAULT_CONFIG.XY_OFFSET.suppressEvent }); /** * Specifies the element or elements that the Tooltip should be * anchored to on mouseover. * @config context * @type HTMLElement[]/String[] * @default null */ /** * String representing the width of the Tooltip. <em>Please note: * </em> As of version 2.3 if either no value or a value of "auto" * is specified, and the Toolip's "container" configuration property * is set to something other than <code>document.body</code> or * its "context" element resides outside the immediately visible * portion of the document, the width of the Tooltip will be * calculated based on the offsetWidth of its root HTML and set just * before it is made visible. The original value will be * restored when the Tooltip is hidden. This ensures the Tooltip is * rendered at a usable width. For more information see * YUILibrary bug #1685496 and YUILibrary * bug #1735423. * @config width * @type String * @default null */ }, // BEGIN BUILT-IN PROPERTY EVENT HANDLERS // /** * The default event handler fired when the "text" property is changed. * @method configText * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configText: function (type, args, obj) { var text = args[0]; if (text) { this.setBody(text); } }, /** * The default event handler fired when the "container" property * is changed. * @method configContainer * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For * configuration handlers, args[0] will equal the newly applied value * for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configContainer: function (type, args, obj) { var container = args[0]; if (typeof container == 'string') { this.cfg.setProperty("container", document.getElementById(container), true); } }, /** * @method _removeEventListeners * @description Removes all of the DOM event handlers from the HTML * element(s) that trigger the display of the tooltip. * @protected */ _removeEventListeners: function () { var aElements = this._context, nElements, oElement, i; if (aElements) { nElements = aElements.length; if (nElements > 0) { i = nElements - 1; do { oElement = aElements[i]; Event.removeListener(oElement, "mouseover", this.onContextMouseOver); Event.removeListener(oElement, "mousemove", this.onContextMouseMove); Event.removeListener(oElement, "mouseout", this.onContextMouseOut); } while (i--); } } }, /** * The default event handler fired when the "context" property * is changed. * @method configContext * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configContext: function (type, args, obj) { var context = args[0], aElements, nElements, oElement, i; if (context) { // Normalize parameter into an array if (! (context instanceof Array)) { if (typeof context == "string") { this.cfg.setProperty("context", [document.getElementById(context)], true); } else { // Assuming this is an element this.cfg.setProperty("context", [context], true); } context = this.cfg.getProperty("context"); } // Remove any existing mouseover/mouseout listeners this._removeEventListeners(); // Add mouseover/mouseout listeners to context elements this._context = context; aElements = this._context; if (aElements) { nElements = aElements.length; if (nElements > 0) { i = nElements - 1; do { oElement = aElements[i]; Event.on(oElement, "mouseover", this.onContextMouseOver, this); Event.on(oElement, "mousemove", this.onContextMouseMove, this); Event.on(oElement, "mouseout", this.onContextMouseOut, this); } while (i--); } } } }, // END BUILT-IN PROPERTY EVENT HANDLERS // // BEGIN BUILT-IN DOM EVENT HANDLERS // /** * The default event handler fired when the user moves the mouse while * over the context element. * @method onContextMouseMove * @param {DOMEvent} e The current DOM event * @param {Object} obj The object argument */ onContextMouseMove: function (e, obj) { obj.pageX = Event.getPageX(e); obj.pageY = Event.getPageY(e); }, /** * The default event handler fired when the user mouses over the * context element. * @method onContextMouseOver * @param {DOMEvent} e The current DOM event * @param {Object} obj The object argument */ onContextMouseOver: function (e, obj) { var context = this; if (context.title) { obj._tempTitle = context.title; context.title = ""; } // Fire first, to honor disabled set in the listner if (obj.fireEvent("contextMouseOver", context, e) !== false && !obj.cfg.getProperty("disabled")) { // Stop the tooltip from being hidden (set on last mouseout) if (obj.hideProcId) { clearTimeout(obj.hideProcId); obj.logger.log("Clearing hide timer: " + obj.hideProcId, "time"); obj.hideProcId = null; } Event.on(context, "mousemove", obj.onContextMouseMove, obj); /** * The unique process ID associated with the thread responsible * for showing the Tooltip. * @type int */ obj.showProcId = obj.doShow(e, context); obj.logger.log("Setting show tooltip timeout: " + obj.showProcId, "time"); } }, /** * The default event handler fired when the user mouses out of * the context element. * @method onContextMouseOut * @param {DOMEvent} e The current DOM event * @param {Object} obj The object argument */ onContextMouseOut: function (e, obj) { var el = this; if (obj._tempTitle) { el.title = obj._tempTitle; obj._tempTitle = null; } if (obj.showProcId) { clearTimeout(obj.showProcId); obj.logger.log("Clearing show timer: " + obj.showProcId, "time"); obj.showProcId = null; } if (obj.hideProcId) { clearTimeout(obj.hideProcId); obj.logger.log("Clearing hide timer: " + obj.hideProcId, "time"); obj.hideProcId = null; } obj.fireEvent("contextMouseOut", el, e); obj.hideProcId = setTimeout(function () { obj.hide(); }, obj.cfg.getProperty("hidedelay")); }, // END BUILT-IN DOM EVENT HANDLERS // /** * Processes the showing of the Tooltip by setting the timeout delay * and offset of the Tooltip. * @method doShow * @param {DOMEvent} e The current DOM event * @param {HTMLElement} context The current context element * @return {Number} The process ID of the timeout function associated * with doShow */ doShow: function (e, context) { var offset = this.cfg.getProperty("xyoffset"), xOffset = offset[0], yOffset = offset[1], me = this; if (UA.opera && context.tagName && context.tagName.toUpperCase() == "A") { yOffset += 12; } return setTimeout(function () { var txt = me.cfg.getProperty("text"); // title does not over-ride text if (me._tempTitle && (txt === "" || YAHOO.lang.isUndefined(txt) || YAHOO.lang.isNull(txt))) { me.setBody(me._tempTitle); } else { me.cfg.refireEvent("text"); } me.logger.log("Show tooltip", "time"); me.moveTo(me.pageX + xOffset, me.pageY + yOffset); if (me.cfg.getProperty("preventoverlap")) { me.preventOverlap(me.pageX, me.pageY); } Event.removeListener(context, "mousemove", me.onContextMouseMove); me.contextTriggerEvent.fire(context); me.show(); me.hideProcId = me.doHide(); me.logger.log("Hide tooltip time active: " + me.hideProcId, "time"); }, this.cfg.getProperty("showdelay")); }, /** * Sets the timeout for the auto-dismiss delay, which by default is 5 * seconds, meaning that a tooltip will automatically dismiss itself * after 5 seconds of being displayed. * @method doHide */ doHide: function () { var me = this; me.logger.log("Setting hide tooltip timeout", "time"); return setTimeout(function () { me.logger.log("Hide tooltip", "time"); me.hide(); }, this.cfg.getProperty("autodismissdelay")); }, /** * Fired when the Tooltip is moved, this event handler is used to * prevent the Tooltip from overlapping with its context element. * @method preventOverlay * @param {Number} pageX The x coordinate position of the mouse pointer * @param {Number} pageY The y coordinate position of the mouse pointer */ preventOverlap: function (pageX, pageY) { var height = this.element.offsetHeight, mousePoint = new YAHOO.util.Point(pageX, pageY), elementRegion = Dom.getRegion(this.element); elementRegion.top -= 5; elementRegion.left -= 5; elementRegion.right += 5; elementRegion.bottom += 5; this.logger.log("context " + elementRegion, "ttip"); this.logger.log("mouse " + mousePoint, "ttip"); if (elementRegion.contains(mousePoint)) { this.logger.log("OVERLAP", "warn"); this.cfg.setProperty("y", (pageY - height - 5)); } }, /** * @method onRender * @description "render" event handler for the Tooltip. * @param {String} p_sType String representing the name of the event * that was fired. * @param {Array} p_aArgs Array of arguments sent when the event * was fired. */ onRender: function (p_sType, p_aArgs) { function sizeShadow() { var oElement = this.element, oShadow = this.underlay; if (oShadow) { oShadow.style.width = (oElement.offsetWidth + 6) + "px"; oShadow.style.height = (oElement.offsetHeight + 1) + "px"; } } function addShadowVisibleClass() { Dom.addClass(this.underlay, "yui-tt-shadow-visible"); if (UA.ie) { this.forceUnderlayRedraw(); } } function removeShadowVisibleClass() { Dom.removeClass(this.underlay, "yui-tt-shadow-visible"); } function createShadow() { var oShadow = this.underlay, oElement, Module, nIE, me; if (!oShadow) { oElement = this.element; Module = YAHOO.widget.Module; nIE = UA.ie; me = this; if (!m_oShadowTemplate) { m_oShadowTemplate = document.createElement("div"); m_oShadowTemplate.className = "yui-tt-shadow"; } oShadow = m_oShadowTemplate.cloneNode(false); oElement.appendChild(oShadow); this.underlay = oShadow; // Backward compatibility, even though it's probably // intended to be "private", it isn't marked as such in the api docs this._shadow = this.underlay; addShadowVisibleClass.call(this); this.subscribe("beforeShow", addShadowVisibleClass); this.subscribe("hide", removeShadowVisibleClass); if (bIEQuirks) { window.setTimeout(function () { sizeShadow.call(me); }, 0); this.cfg.subscribeToConfigEvent("width", sizeShadow); this.cfg.subscribeToConfigEvent("height", sizeShadow); this.subscribe("changeContent", sizeShadow); Module.textResizeEvent.subscribe(sizeShadow, this, true); this.subscribe("destroy", function () { Module.textResizeEvent.unsubscribe(sizeShadow, this); }); } } } function onBeforeShow() { createShadow.call(this); this.unsubscribe("beforeShow", onBeforeShow); } if (this.cfg.getProperty("visible")) { createShadow.call(this); } else { this.subscribe("beforeShow", onBeforeShow); } }, /** * Forces the underlay element to be repainted, through the application/removal * of a yui-force-redraw class to the underlay element. * * @method forceUnderlayRedraw */ forceUnderlayRedraw : function() { var tt = this; Dom.addClass(tt.underlay, "yui-force-redraw"); setTimeout(function() {Dom.removeClass(tt.underlay, "yui-force-redraw");}, 0); }, /** * Removes the Tooltip element from the DOM and sets all child * elements to null. * @method destroy */ destroy: function () { // Remove any existing mouseover/mouseout listeners this._removeEventListeners(); Tooltip.superclass.destroy.call(this); }, /** * Returns a string representation of the object. * @method toString * @return {String} The string representation of the Tooltip */ toString: function () { return "Tooltip " + this.id; } }); }()); (function () { /** * Panel is an implementation of Overlay that behaves like an OS window, * with a draggable header and an optional close icon at the top right. * @namespace YAHOO.widget * @class Panel * @extends YAHOO.widget.Overlay * @constructor * @param {String} el The element ID representing the Panel <em>OR</em> * @param {HTMLElement} el The element representing the Panel * @param {Object} userConfig The configuration object literal containing * the configuration that should be set for this Panel. See configuration * documentation for more details. */ YAHOO.widget.Panel = function (el, userConfig) { YAHOO.widget.Panel.superclass.constructor.call(this, el, userConfig); }; var _currentModal = null; var Lang = YAHOO.lang, Util = YAHOO.util, Dom = Util.Dom, Event = Util.Event, CustomEvent = Util.CustomEvent, KeyListener = YAHOO.util.KeyListener, Config = Util.Config, Overlay = YAHOO.widget.Overlay, Panel = YAHOO.widget.Panel, UA = YAHOO.env.ua, bIEQuirks = (UA.ie && (UA.ie <= 6 || document.compatMode == "BackCompat")), m_oMaskTemplate, m_oUnderlayTemplate, m_oCloseIconTemplate, /** * Constant representing the name of the Panel's events * @property EVENT_TYPES * @private * @final * @type Object */ EVENT_TYPES = { "BEFORE_SHOW_MASK" : "beforeShowMask", "BEFORE_HIDE_MASK" : "beforeHideMask", "SHOW_MASK": "showMask", "HIDE_MASK": "hideMask", "DRAG": "drag" }, /** * Constant representing the Panel's configuration properties * @property DEFAULT_CONFIG * @private * @final * @type Object */ DEFAULT_CONFIG = { "CLOSE": { key: "close", value: true, validator: Lang.isBoolean, supercedes: ["visible"] }, "DRAGGABLE": { key: "draggable", value: (Util.DD ? true : false), validator: Lang.isBoolean, supercedes: ["visible"] }, "DRAG_ONLY" : { key: "dragonly", value: false, validator: Lang.isBoolean, supercedes: ["draggable"] }, "UNDERLAY": { key: "underlay", value: "shadow", supercedes: ["visible"] }, "MODAL": { key: "modal", value: false, validator: Lang.isBoolean, supercedes: ["visible", "zindex"] }, "KEY_LISTENERS": { key: "keylisteners", suppressEvent: true, supercedes: ["visible"] }, "STRINGS" : { key: "strings", supercedes: ["close"], validator: Lang.isObject, value: { close: "Close" } } }; /** * Constant representing the default CSS class used for a Panel * @property YAHOO.widget.Panel.CSS_PANEL * @static * @final * @type String */ Panel.CSS_PANEL = "yui-panel"; /** * Constant representing the default CSS class used for a Panel's * wrapping container * @property YAHOO.widget.Panel.CSS_PANEL_CONTAINER * @static * @final * @type String */ Panel.CSS_PANEL_CONTAINER = "yui-panel-container"; /** * Constant representing the default set of focusable elements * on the pagewhich Modal Panels will prevent access to, when * the modal mask is displayed * * @property YAHOO.widget.Panel.FOCUSABLE * @static * @type Array */ Panel.FOCUSABLE = [ "a", "button", "select", "textarea", "input", "iframe" ]; // Private CustomEvent listeners /* "beforeRender" event handler that creates an empty header for a Panel instance if its "draggable" configuration property is set to "true" and no header has been created. */ function createHeader(p_sType, p_aArgs) { if (!this.header && this.cfg.getProperty("draggable")) { this.setHeader("&#160;"); } } /* "hide" event handler that sets a Panel instance's "width" configuration property back to its original value before "setWidthToOffsetWidth" was called. */ function restoreOriginalWidth(p_sType, p_aArgs, p_oObject) { var sOriginalWidth = p_oObject[0], sNewWidth = p_oObject[1], oConfig = this.cfg, sCurrentWidth = oConfig.getProperty("width"); if (sCurrentWidth == sNewWidth) { oConfig.setProperty("width", sOriginalWidth); } this.unsubscribe("hide", restoreOriginalWidth, p_oObject); } /* "beforeShow" event handler that sets a Panel instance's "width" configuration property to the value of its root HTML elements's offsetWidth */ function setWidthToOffsetWidth(p_sType, p_aArgs) { var oConfig, sOriginalWidth, sNewWidth; if (bIEQuirks) { oConfig = this.cfg; sOriginalWidth = oConfig.getProperty("width"); if (!sOriginalWidth || sOriginalWidth == "auto") { sNewWidth = (this.element.offsetWidth + "px"); oConfig.setProperty("width", sNewWidth); this.subscribe("hide", restoreOriginalWidth, [(sOriginalWidth || ""), sNewWidth]); } } } YAHOO.extend(Panel, Overlay, { /** * The Overlay initialization method, which is executed for Overlay and * all of its subclasses. This method is automatically called by the * constructor, and sets up all DOM references for pre-existing markup, * and creates required markup if it is not already present. * @method init * @param {String} el The element ID representing the Overlay <em>OR</em> * @param {HTMLElement} el The element representing the Overlay * @param {Object} userConfig The configuration object literal * containing the configuration that should be set for this Overlay. * See configuration documentation for more details. */ init: function (el, userConfig) { /* Note that we don't pass the user config in here yet because we only want it executed once, at the lowest subclass level */ Panel.superclass.init.call(this, el/*, userConfig*/); this.beforeInitEvent.fire(Panel); Dom.addClass(this.element, Panel.CSS_PANEL); this.buildWrapper(); if (userConfig) { this.cfg.applyConfig(userConfig, true); } this.subscribe("showMask", this._addFocusHandlers); this.subscribe("hideMask", this._removeFocusHandlers); this.subscribe("beforeRender", createHeader); this.subscribe("render", function() { this.setFirstLastFocusable(); this.subscribe("changeContent", this.setFirstLastFocusable); }); this.subscribe("show", this._focusOnShow); this.initEvent.fire(Panel); }, /** * @method _onElementFocus * @private * * "focus" event handler for a focuable element. Used to automatically * blur the element when it receives focus to ensure that a Panel * instance's modality is not compromised. * * @param {Event} e The DOM event object */ _onElementFocus : function(e){ if(_currentModal === this) { var target = Event.getTarget(e), doc = document.documentElement, insideDoc = (target !== doc && target !== window); // mask and documentElement checks added for IE, which focuses on the mask when it's clicked on, and focuses on // the documentElement, when the document scrollbars are clicked on if (insideDoc && target !== this.element && target !== this.mask && !Dom.isAncestor(this.element, target)) { try { this._focusFirstModal(); } catch(err){ // Just in case we fail to focus try { if (insideDoc && target !== document.body) { target.blur(); } } catch(err2) { } } } } }, /** * Focuses on the first element if present, otherwise falls back to the focus mechanisms used for * modality. This method does not try/catch focus failures. The caller is responsible for catching exceptions, * and taking remedial measures. * * @method _focusFirstModal */ _focusFirstModal : function() { var el = this.firstElement; if (el) { el.focus(); } else { if (this._modalFocus) { this._modalFocus.focus(); } else { this.innerElement.focus(); } } }, /** * @method _addFocusHandlers * @protected * * "showMask" event handler that adds a "focus" event handler to all * focusable elements in the document to enforce a Panel instance's * modality from being compromised. * * @param p_sType {String} Custom event type * @param p_aArgs {Array} Custom event arguments */ _addFocusHandlers: function(p_sType, p_aArgs) { if (!this.firstElement) { if (UA.webkit || UA.opera) { if (!this._modalFocus) { this._createHiddenFocusElement(); } } else { this.innerElement.tabIndex = 0; } } this._setTabLoop(this.firstElement, this.lastElement); Event.onFocus(document.documentElement, this._onElementFocus, this, true); _currentModal = this; }, /** * Creates a hidden focusable element, used to focus on, * to enforce modality for browsers in which focus cannot * be applied to the container box. * * @method _createHiddenFocusElement * @private */ _createHiddenFocusElement : function() { var e = document.createElement("button"); e.style.height = "1px"; e.style.width = "1px"; e.style.position = "absolute"; e.style.left = "-10000em"; e.style.opacity = 0; e.tabIndex = -1; this.innerElement.appendChild(e); this._modalFocus = e; }, /** * @method _removeFocusHandlers * @protected * * "hideMask" event handler that removes all "focus" event handlers added * by the "addFocusEventHandlers" method. * * @param p_sType {String} Event type * @param p_aArgs {Array} Event Arguments */ _removeFocusHandlers: function(p_sType, p_aArgs) { Event.removeFocusListener(document.documentElement, this._onElementFocus, this); if (_currentModal == this) { _currentModal = null; } }, /** * Focus handler for the show event * * @method _focusOnShow * @param {String} type Event Type * @param {Array} args Event arguments * @param {Object} obj Additional data */ _focusOnShow : function(type, args, obj) { if (args && args[1]) { Event.stopEvent(args[1]); } if (!this.focusFirst(type, args, obj)) { if (this.cfg.getProperty("modal")) { this._focusFirstModal(); } } }, /** * Sets focus to the first element in the Panel. * * @method focusFirst * @return {Boolean} true, if successfully focused, false otherwise */ focusFirst: function (type, args, obj) { var el = this.firstElement, focused = false; if (args && args[1]) { Event.stopEvent(args[1]); } if (el) { try { el.focus(); focused = true; } catch(err) { // Ignore } } return focused; }, /** * Sets focus to the last element in the Panel. * * @method focusLast * @return {Boolean} true, if successfully focused, false otherwise */ focusLast: function (type, args, obj) { var el = this.lastElement, focused = false; if (args && args[1]) { Event.stopEvent(args[1]); } if (el) { try { el.focus(); focused = true; } catch(err) { // Ignore } } return focused; }, /** * Protected internal method for setTabLoop, which can be used by * subclasses to jump in and modify the arguments passed in if required. * * @method _setTabLoop * @param {HTMLElement} firstElement * @param {HTMLElement} lastElement * @protected * */ _setTabLoop : function(firstElement, lastElement) { this.setTabLoop(firstElement, lastElement); }, /** * Sets up a tab, shift-tab loop between the first and last elements * provided. NOTE: Sets up the preventBackTab and preventTabOut KeyListener * instance properties, which are reset everytime this method is invoked. * * @method setTabLoop * @param {HTMLElement} firstElement * @param {HTMLElement} lastElement * */ setTabLoop : function(firstElement, lastElement) { var backTab = this.preventBackTab, tab = this.preventTabOut, showEvent = this.showEvent, hideEvent = this.hideEvent; if (backTab) { backTab.disable(); showEvent.unsubscribe(backTab.enable, backTab); hideEvent.unsubscribe(backTab.disable, backTab); backTab = this.preventBackTab = null; } if (tab) { tab.disable(); showEvent.unsubscribe(tab.enable, tab); hideEvent.unsubscribe(tab.disable,tab); tab = this.preventTabOut = null; } if (firstElement) { this.preventBackTab = new KeyListener(firstElement, {shift:true, keys:9}, {fn:this.focusLast, scope:this, correctScope:true} ); backTab = this.preventBackTab; showEvent.subscribe(backTab.enable, backTab, true); hideEvent.subscribe(backTab.disable,backTab, true); } if (lastElement) { this.preventTabOut = new KeyListener(lastElement, {shift:false, keys:9}, {fn:this.focusFirst, scope:this, correctScope:true} ); tab = this.preventTabOut; showEvent.subscribe(tab.enable, tab, true); hideEvent.subscribe(tab.disable,tab, true); } }, /** * Returns an array of the currently focusable items which reside within * Panel. The set of focusable elements the method looks for are defined * in the Panel.FOCUSABLE static property * * @method getFocusableElements * @param {HTMLElement} root element to start from. */ getFocusableElements : function(root) { root = root || this.innerElement; var focusable = {}, panel = this; for (var i = 0; i < Panel.FOCUSABLE.length; i++) { focusable[Panel.FOCUSABLE[i]] = true; } // Not looking by Tag, since we want elements in DOM order return Dom.getElementsBy(function(el) { return panel._testIfFocusable(el, focusable); }, null, root); }, /** * This is the test method used by getFocusableElements, to determine which elements to * include in the focusable elements list. Users may override this to customize behavior. * * @method _testIfFocusable * @param {Object} el The element being tested * @param {Object} focusable The hash of known focusable elements, created by an array-to-map operation on Panel.FOCUSABLE * @protected */ _testIfFocusable: function(el, focusable) { if (el.focus && el.type !== "hidden" && !el.disabled && focusable[el.tagName.toLowerCase()]) { return true; } return false; }, /** * Sets the firstElement and lastElement instance properties * to the first and last focusable elements in the Panel. * * @method setFirstLastFocusable */ setFirstLastFocusable : function() { this.firstElement = null; this.lastElement = null; var elements = this.getFocusableElements(); this.focusableElements = elements; if (elements.length > 0) { this.firstElement = elements[0]; this.lastElement = elements[elements.length - 1]; } if (this.cfg.getProperty("modal")) { this._setTabLoop(this.firstElement, this.lastElement); } }, /** * Initializes the custom events for Module which are fired * automatically at appropriate times by the Module class. */ initEvents: function () { Panel.superclass.initEvents.call(this); var SIGNATURE = CustomEvent.LIST; /** * CustomEvent fired after the modality mask is shown * @event showMaskEvent */ this.showMaskEvent = this.createEvent(EVENT_TYPES.SHOW_MASK); this.showMaskEvent.signature = SIGNATURE; /** * CustomEvent fired before the modality mask is shown. Subscribers can return false to prevent the * mask from being shown * @event beforeShowMaskEvent */ this.beforeShowMaskEvent = this.createEvent(EVENT_TYPES.BEFORE_SHOW_MASK); this.beforeShowMaskEvent.signature = SIGNATURE; /** * CustomEvent fired after the modality mask is hidden * @event hideMaskEvent */ this.hideMaskEvent = this.createEvent(EVENT_TYPES.HIDE_MASK); this.hideMaskEvent.signature = SIGNATURE; /** * CustomEvent fired before the modality mask is hidden. Subscribers can return false to prevent the * mask from being hidden * @event beforeHideMaskEvent */ this.beforeHideMaskEvent = this.createEvent(EVENT_TYPES.BEFORE_HIDE_MASK); this.beforeHideMaskEvent.signature = SIGNATURE; /** * CustomEvent when the Panel is dragged * @event dragEvent */ this.dragEvent = this.createEvent(EVENT_TYPES.DRAG); this.dragEvent.signature = SIGNATURE; }, /** * Initializes the class's configurable properties which can be changed * using the Panel's Config object (cfg). * @method initDefaultConfig */ initDefaultConfig: function () { Panel.superclass.initDefaultConfig.call(this); // Add panel config properties // /** * True if the Panel should display a "close" button * @config close * @type Boolean * @default true */ this.cfg.addProperty(DEFAULT_CONFIG.CLOSE.key, { handler: this.configClose, value: DEFAULT_CONFIG.CLOSE.value, validator: DEFAULT_CONFIG.CLOSE.validator, supercedes: DEFAULT_CONFIG.CLOSE.supercedes }); /** * Boolean specifying if the Panel should be draggable. The default * value is "true" if the Drag and Drop utility is included, * otherwise it is "false." <strong>PLEASE NOTE:</strong> There is a * known issue in IE 6 (Strict Mode and Quirks Mode) and IE 7 * (Quirks Mode) where Panels that either don't have a value set for * their "width" configuration property, or their "width" * configuration property is set to "auto" will only be draggable by * placing the mouse on the text of the Panel's header element. * To fix this bug, draggable Panels missing a value for their * "width" configuration property, or whose "width" configuration * property is set to "auto" will have it set to the value of * their root HTML element's offsetWidth before they are made * visible. The calculated width is then removed when the Panel is * hidden. <em>This fix is only applied to draggable Panels in IE 6 * (Strict Mode and Quirks Mode) and IE 7 (Quirks Mode)</em>. For * more information on this issue see: * YUILibrary bugs #1726972 and #1589210. * @config draggable * @type Boolean * @default true */ this.cfg.addProperty(DEFAULT_CONFIG.DRAGGABLE.key, { handler: this.configDraggable, value: (Util.DD) ? true : false, validator: DEFAULT_CONFIG.DRAGGABLE.validator, supercedes: DEFAULT_CONFIG.DRAGGABLE.supercedes }); /** * Boolean specifying if the draggable Panel should be drag only, not interacting with drop * targets on the page. * <p> * When set to true, draggable Panels will not check to see if they are over drop targets, * or fire the DragDrop events required to support drop target interaction (onDragEnter, * onDragOver, onDragOut, onDragDrop etc.). * If the Panel is not designed to be dropped on any target elements on the page, then this * flag can be set to true to improve performance. * </p> * <p> * When set to false, all drop target related events will be fired. * </p> * <p> * The property is set to false by default to maintain backwards compatibility but should be * set to true if drop target interaction is not required for the Panel, to improve performance.</p> * * @config dragOnly * @type Boolean * @default false */ this.cfg.addProperty(DEFAULT_CONFIG.DRAG_ONLY.key, { value: DEFAULT_CONFIG.DRAG_ONLY.value, validator: DEFAULT_CONFIG.DRAG_ONLY.validator, supercedes: DEFAULT_CONFIG.DRAG_ONLY.supercedes }); /** * Sets the type of underlay to display for the Panel. Valid values * are "shadow," "matte," and "none". <strong>PLEASE NOTE:</strong> * The creation of the underlay element is deferred until the Panel * is initially made visible. For Gecko-based browsers on Mac * OS X the underlay elment is always created as it is used as a * shim to prevent Aqua scrollbars below a Panel instance from poking * through it (See YUILibrary bug #1723530). * @config underlay * @type String * @default shadow */ this.cfg.addProperty(DEFAULT_CONFIG.UNDERLAY.key, { handler: this.configUnderlay, value: DEFAULT_CONFIG.UNDERLAY.value, supercedes: DEFAULT_CONFIG.UNDERLAY.supercedes }); /** * True if the Panel should be displayed in a modal fashion, * automatically creating a transparent mask over the document that * will not be removed until the Panel is dismissed. * @config modal * @type Boolean * @default false */ this.cfg.addProperty(DEFAULT_CONFIG.MODAL.key, { handler: this.configModal, value: DEFAULT_CONFIG.MODAL.value, validator: DEFAULT_CONFIG.MODAL.validator, supercedes: DEFAULT_CONFIG.MODAL.supercedes }); /** * A KeyListener (or array of KeyListeners) that will be enabled * when the Panel is shown, and disabled when the Panel is hidden. * @config keylisteners * @type YAHOO.util.KeyListener[] * @default null */ this.cfg.addProperty(DEFAULT_CONFIG.KEY_LISTENERS.key, { handler: this.configKeyListeners, suppressEvent: DEFAULT_CONFIG.KEY_LISTENERS.suppressEvent, supercedes: DEFAULT_CONFIG.KEY_LISTENERS.supercedes }); /** * UI Strings used by the Panel. The strings are inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * * @config strings * @type Object * @default An object literal with the properties shown below: * <dl> * <dt>close</dt><dd><em>HTML</em> : The markup to use as the label for the close icon. Defaults to "Close".</dd> * </dl> */ this.cfg.addProperty(DEFAULT_CONFIG.STRINGS.key, { value:DEFAULT_CONFIG.STRINGS.value, handler:this.configStrings, validator:DEFAULT_CONFIG.STRINGS.validator, supercedes:DEFAULT_CONFIG.STRINGS.supercedes }); }, // BEGIN BUILT-IN PROPERTY EVENT HANDLERS // /** * The default event handler fired when the "close" property is changed. * The method controls the appending or hiding of the close icon at the * top right of the Panel. * @method configClose * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configClose: function (type, args, obj) { var val = args[0], oClose = this.close, strings = this.cfg.getProperty("strings"), fc; if (val) { if (!oClose) { if (!m_oCloseIconTemplate) { m_oCloseIconTemplate = document.createElement("a"); m_oCloseIconTemplate.className = "container-close"; m_oCloseIconTemplate.href = "#"; } oClose = m_oCloseIconTemplate.cloneNode(true); fc = this.innerElement.firstChild; if (fc) { this.innerElement.insertBefore(oClose, fc); } else { this.innerElement.appendChild(oClose); } oClose.innerHTML = (strings && strings.close) ? strings.close : "&#160;"; Event.on(oClose, "click", this._doClose, this, true); this.close = oClose; } else { oClose.style.display = "block"; } } else { if (oClose) { oClose.style.display = "none"; } } }, /** * Event handler for the close icon * * @method _doClose * @protected * * @param {DOMEvent} e */ _doClose : function (e) { Event.preventDefault(e); this.hide(); }, /** * The default event handler fired when the "draggable" property * is changed. * @method configDraggable * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configDraggable: function (type, args, obj) { var val = args[0]; if (val) { if (!Util.DD) { YAHOO.log("DD dependency not met.", "error"); this.cfg.setProperty("draggable", false); return; } if (this.header) { Dom.setStyle(this.header, "cursor", "move"); this.registerDragDrop(); } this.subscribe("beforeShow", setWidthToOffsetWidth); } else { if (this.dd) { this.dd.unreg(); } if (this.header) { Dom.setStyle(this.header,"cursor","auto"); } this.unsubscribe("beforeShow", setWidthToOffsetWidth); } }, /** * The default event handler fired when the "underlay" property * is changed. * @method configUnderlay * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configUnderlay: function (type, args, obj) { var bMacGecko = (this.platform == "mac" && UA.gecko), sUnderlay = args[0].toLowerCase(), oUnderlay = this.underlay, oElement = this.element; function createUnderlay() { var bNew = false; if (!oUnderlay) { // create if not already in DOM if (!m_oUnderlayTemplate) { m_oUnderlayTemplate = document.createElement("div"); m_oUnderlayTemplate.className = "underlay"; } oUnderlay = m_oUnderlayTemplate.cloneNode(false); this.element.appendChild(oUnderlay); this.underlay = oUnderlay; if (bIEQuirks) { this.sizeUnderlay(); this.cfg.subscribeToConfigEvent("width", this.sizeUnderlay); this.cfg.subscribeToConfigEvent("height", this.sizeUnderlay); this.changeContentEvent.subscribe(this.sizeUnderlay); YAHOO.widget.Module.textResizeEvent.subscribe(this.sizeUnderlay, this, true); } if (UA.webkit && UA.webkit < 420) { this.changeContentEvent.subscribe(this.forceUnderlayRedraw); } bNew = true; } } function onBeforeShow() { var bNew = createUnderlay.call(this); if (!bNew && bIEQuirks) { this.sizeUnderlay(); } this._underlayDeferred = false; this.beforeShowEvent.unsubscribe(onBeforeShow); } function destroyUnderlay() { if (this._underlayDeferred) { this.beforeShowEvent.unsubscribe(onBeforeShow); this._underlayDeferred = false; } if (oUnderlay) { this.cfg.unsubscribeFromConfigEvent("width", this.sizeUnderlay); this.cfg.unsubscribeFromConfigEvent("height",this.sizeUnderlay); this.changeContentEvent.unsubscribe(this.sizeUnderlay); this.changeContentEvent.unsubscribe(this.forceUnderlayRedraw); YAHOO.widget.Module.textResizeEvent.unsubscribe(this.sizeUnderlay, this, true); this.element.removeChild(oUnderlay); this.underlay = null; } } switch (sUnderlay) { case "shadow": Dom.removeClass(oElement, "matte"); Dom.addClass(oElement, "shadow"); break; case "matte": if (!bMacGecko) { destroyUnderlay.call(this); } Dom.removeClass(oElement, "shadow"); Dom.addClass(oElement, "matte"); break; default: if (!bMacGecko) { destroyUnderlay.call(this); } Dom.removeClass(oElement, "shadow"); Dom.removeClass(oElement, "matte"); break; } if ((sUnderlay == "shadow") || (bMacGecko && !oUnderlay)) { if (this.cfg.getProperty("visible")) { var bNew = createUnderlay.call(this); if (!bNew && bIEQuirks) { this.sizeUnderlay(); } } else { if (!this._underlayDeferred) { this.beforeShowEvent.subscribe(onBeforeShow); this._underlayDeferred = true; } } } }, /** * The default event handler fired when the "modal" property is * changed. This handler subscribes or unsubscribes to the show and hide * events to handle the display or hide of the modality mask. * @method configModal * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configModal: function (type, args, obj) { var modal = args[0]; if (modal) { if (!this._hasModalityEventListeners) { this.subscribe("beforeShow", this.buildMask); this.subscribe("beforeShow", this.bringToTop); this.subscribe("beforeShow", this.showMask); this.subscribe("hide", this.hideMask); Overlay.windowResizeEvent.subscribe(this.sizeMask, this, true); this._hasModalityEventListeners = true; } } else { if (this._hasModalityEventListeners) { if (this.cfg.getProperty("visible")) { this.hideMask(); this.removeMask(); } this.unsubscribe("beforeShow", this.buildMask); this.unsubscribe("beforeShow", this.bringToTop); this.unsubscribe("beforeShow", this.showMask); this.unsubscribe("hide", this.hideMask); Overlay.windowResizeEvent.unsubscribe(this.sizeMask, this); this._hasModalityEventListeners = false; } } }, /** * Removes the modality mask. * @method removeMask */ removeMask: function () { var oMask = this.mask, oParentNode; if (oMask) { /* Hide the mask before destroying it to ensure that DOM event handlers on focusable elements get removed. */ this.hideMask(); oParentNode = oMask.parentNode; if (oParentNode) { oParentNode.removeChild(oMask); } this.mask = null; } }, /** * The default event handler fired when the "keylisteners" property * is changed. * @method configKeyListeners * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configKeyListeners: function (type, args, obj) { var listeners = args[0], listener, nListeners, i; if (listeners) { if (listeners instanceof Array) { nListeners = listeners.length; for (i = 0; i < nListeners; i++) { listener = listeners[i]; if (!Config.alreadySubscribed(this.showEvent, listener.enable, listener)) { this.showEvent.subscribe(listener.enable, listener, true); } if (!Config.alreadySubscribed(this.hideEvent, listener.disable, listener)) { this.hideEvent.subscribe(listener.disable, listener, true); this.destroyEvent.subscribe(listener.disable, listener, true); } } } else { if (!Config.alreadySubscribed(this.showEvent, listeners.enable, listeners)) { this.showEvent.subscribe(listeners.enable, listeners, true); } if (!Config.alreadySubscribed(this.hideEvent, listeners.disable, listeners)) { this.hideEvent.subscribe(listeners.disable, listeners, true); this.destroyEvent.subscribe(listeners.disable, listeners, true); } } } }, /** * The default handler for the "strings" property * @method configStrings */ configStrings : function(type, args, obj) { var val = Lang.merge(DEFAULT_CONFIG.STRINGS.value, args[0]); this.cfg.setProperty(DEFAULT_CONFIG.STRINGS.key, val, true); }, /** * The default event handler fired when the "height" property is changed. * @method configHeight * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configHeight: function (type, args, obj) { var height = args[0], el = this.innerElement; Dom.setStyle(el, "height", height); this.cfg.refireEvent("iframe"); }, /** * The default custom event handler executed when the Panel's height is changed, * if the autofillheight property has been set. * * @method _autoFillOnHeightChange * @protected * @param {String} type The event type * @param {Array} args The array of arguments passed to event subscribers * @param {HTMLElement} el The header, body or footer element which is to be resized to fill * out the containers height */ _autoFillOnHeightChange : function(type, args, el) { Panel.superclass._autoFillOnHeightChange.apply(this, arguments); if (bIEQuirks) { var panel = this; setTimeout(function() { panel.sizeUnderlay(); },0); } }, /** * The default event handler fired when the "width" property is changed. * @method configWidth * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configWidth: function (type, args, obj) { var width = args[0], el = this.innerElement; Dom.setStyle(el, "width", width); this.cfg.refireEvent("iframe"); }, /** * The default event handler fired when the "zIndex" property is changed. * @method configzIndex * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configzIndex: function (type, args, obj) { Panel.superclass.configzIndex.call(this, type, args, obj); if (this.mask || this.cfg.getProperty("modal") === true) { var panelZ = Dom.getStyle(this.element, "zIndex"); if (!panelZ || isNaN(panelZ)) { panelZ = 0; } if (panelZ === 0) { // Recursive call to configzindex (which should be stopped // from going further because panelZ should no longer === 0) this.cfg.setProperty("zIndex", 1); } else { this.stackMask(); } } }, // END BUILT-IN PROPERTY EVENT HANDLERS // /** * Builds the wrapping container around the Panel that is used for * positioning the shadow and matte underlays. The container element is * assigned to a local instance variable called container, and the * element is reinserted inside of it. * @method buildWrapper */ buildWrapper: function () { var elementParent = this.element.parentNode, originalElement = this.element, wrapper = document.createElement("div"); wrapper.className = Panel.CSS_PANEL_CONTAINER; wrapper.id = originalElement.id + "_c"; if (elementParent) { elementParent.insertBefore(wrapper, originalElement); } wrapper.appendChild(originalElement); this.element = wrapper; this.innerElement = originalElement; Dom.setStyle(this.innerElement, "visibility", "inherit"); }, /** * Adjusts the size of the shadow based on the size of the element. * @method sizeUnderlay */ sizeUnderlay: function () { var oUnderlay = this.underlay, oElement; if (oUnderlay) { oElement = this.element; oUnderlay.style.width = oElement.offsetWidth + "px"; oUnderlay.style.height = oElement.offsetHeight + "px"; } }, /** * Registers the Panel's header for drag & drop capability. * @method registerDragDrop */ registerDragDrop: function () { var me = this; if (this.header) { if (!Util.DD) { YAHOO.log("DD dependency not met.", "error"); return; } var bDragOnly = (this.cfg.getProperty("dragonly") === true); /** * The YAHOO.util.DD instance, used to implement the draggable header for the panel if draggable is enabled * * @property dd * @type YAHOO.util.DD */ this.dd = new Util.DD(this.element.id, this.id, {dragOnly: bDragOnly}); if (!this.header.id) { this.header.id = this.id + "_h"; } this.dd.startDrag = function () { var offsetHeight, offsetWidth, viewPortWidth, viewPortHeight, scrollX, scrollY; if (YAHOO.env.ua.ie == 6) { Dom.addClass(me.element,"drag"); } if (me.cfg.getProperty("constraintoviewport")) { var nViewportOffset = Overlay.VIEWPORT_OFFSET; offsetHeight = me.element.offsetHeight; offsetWidth = me.element.offsetWidth; viewPortWidth = Dom.getViewportWidth(); viewPortHeight = Dom.getViewportHeight(); scrollX = Dom.getDocumentScrollLeft(); scrollY = Dom.getDocumentScrollTop(); if (offsetHeight + nViewportOffset < viewPortHeight) { this.minY = scrollY + nViewportOffset; this.maxY = scrollY + viewPortHeight - offsetHeight - nViewportOffset; } else { this.minY = scrollY + nViewportOffset; this.maxY = scrollY + nViewportOffset; } if (offsetWidth + nViewportOffset < viewPortWidth) { this.minX = scrollX + nViewportOffset; this.maxX = scrollX + viewPortWidth - offsetWidth - nViewportOffset; } else { this.minX = scrollX + nViewportOffset; this.maxX = scrollX + nViewportOffset; } this.constrainX = true; this.constrainY = true; } else { this.constrainX = false; this.constrainY = false; } me.dragEvent.fire("startDrag", arguments); }; this.dd.onDrag = function () { me.syncPosition(); me.cfg.refireEvent("iframe"); if (this.platform == "mac" && YAHOO.env.ua.gecko) { this.showMacGeckoScrollbars(); } me.dragEvent.fire("onDrag", arguments); }; this.dd.endDrag = function () { if (YAHOO.env.ua.ie == 6) { Dom.removeClass(me.element,"drag"); } me.dragEvent.fire("endDrag", arguments); me.moveEvent.fire(me.cfg.getProperty("xy")); }; this.dd.setHandleElId(this.header.id); this.dd.addInvalidHandleType("INPUT"); this.dd.addInvalidHandleType("SELECT"); this.dd.addInvalidHandleType("TEXTAREA"); } }, /** * Builds the mask that is laid over the document when the Panel is * configured to be modal. * @method buildMask */ buildMask: function () { var oMask = this.mask; if (!oMask) { if (!m_oMaskTemplate) { m_oMaskTemplate = document.createElement("div"); m_oMaskTemplate.className = "mask"; m_oMaskTemplate.innerHTML = "&#160;"; } oMask = m_oMaskTemplate.cloneNode(true); oMask.id = this.id + "_mask"; document.body.insertBefore(oMask, document.body.firstChild); this.mask = oMask; if (YAHOO.env.ua.gecko && this.platform == "mac") { Dom.addClass(this.mask, "block-scrollbars"); } // Stack mask based on the element zindex this.stackMask(); } }, /** * Hides the modality mask. * @method hideMask */ hideMask: function () { if (this.cfg.getProperty("modal") && this.mask && this.beforeHideMaskEvent.fire()) { this.mask.style.display = "none"; Dom.removeClass(document.body, "masked"); this.hideMaskEvent.fire(); } }, /** * Shows the modality mask. * @method showMask */ showMask: function () { if (this.cfg.getProperty("modal") && this.mask && this.beforeShowMaskEvent.fire()) { Dom.addClass(document.body, "masked"); this.sizeMask(); this.mask.style.display = "block"; this.showMaskEvent.fire(); } }, /** * Sets the size of the modality mask to cover the entire scrollable * area of the document * @method sizeMask */ sizeMask: function () { if (this.mask) { // Shrink mask first, so it doesn't affect the document size. var mask = this.mask, viewWidth = Dom.getViewportWidth(), viewHeight = Dom.getViewportHeight(); if (mask.offsetHeight > viewHeight) { mask.style.height = viewHeight + "px"; } if (mask.offsetWidth > viewWidth) { mask.style.width = viewWidth + "px"; } // Then size it to the document mask.style.height = Dom.getDocumentHeight() + "px"; mask.style.width = Dom.getDocumentWidth() + "px"; } }, /** * Sets the zindex of the mask, if it exists, based on the zindex of * the Panel element. The zindex of the mask is set to be one less * than the Panel element's zindex. * * <p>NOTE: This method will not bump up the zindex of the Panel * to ensure that the mask has a non-negative zindex. If you require the * mask zindex to be 0 or higher, the zindex of the Panel * should be set to a value higher than 0, before this method is called. * </p> * @method stackMask */ stackMask: function() { if (this.mask) { var panelZ = Dom.getStyle(this.element, "zIndex"); if (!YAHOO.lang.isUndefined(panelZ) && !isNaN(panelZ)) { Dom.setStyle(this.mask, "zIndex", panelZ - 1); } } }, /** * Renders the Panel by inserting the elements that are not already in * the main Panel into their correct places. Optionally appends the * Panel to the specified node prior to the render's execution. NOTE: * For Panels without existing markup, the appendToNode argument is * REQUIRED. If this argument is ommitted and the current element is * not present in the document, the function will return false, * indicating that the render was a failure. * @method render * @param {String} appendToNode The element id to which the Module * should be appended to prior to rendering <em>OR</em> * @param {HTMLElement} appendToNode The element to which the Module * should be appended to prior to rendering * @return {boolean} Success or failure of the render */ render: function (appendToNode) { return Panel.superclass.render.call(this, appendToNode, this.innerElement); }, /** * Renders the currently set header into it's proper position under the * module element. If the module element is not provided, "this.innerElement" * is used. * * @method _renderHeader * @protected * @param {HTMLElement} moduleElement Optional. A reference to the module element */ _renderHeader: function(moduleElement){ moduleElement = moduleElement || this.innerElement; Panel.superclass._renderHeader.call(this, moduleElement); }, /** * Renders the currently set body into it's proper position under the * module element. If the module element is not provided, "this.innerElement" * is used. * * @method _renderBody * @protected * @param {HTMLElement} moduleElement Optional. A reference to the module element. */ _renderBody: function(moduleElement){ moduleElement = moduleElement || this.innerElement; Panel.superclass._renderBody.call(this, moduleElement); }, /** * Renders the currently set footer into it's proper position under the * module element. If the module element is not provided, "this.innerElement" * is used. * * @method _renderFooter * @protected * @param {HTMLElement} moduleElement Optional. A reference to the module element */ _renderFooter: function(moduleElement){ moduleElement = moduleElement || this.innerElement; Panel.superclass._renderFooter.call(this, moduleElement); }, /** * Removes the Panel element from the DOM and sets all child elements * to null. * @method destroy * @param {boolean} shallowPurge If true, only the parent element's DOM event listeners are purged. If false, or not provided, all children are also purged of DOM event listeners. * NOTE: The flag is a "shallowPurge" flag, as opposed to what may be a more intuitive "purgeChildren" flag to maintain backwards compatibility with behavior prior to 2.9.0. */ destroy: function (shallowPurge) { Overlay.windowResizeEvent.unsubscribe(this.sizeMask, this); this.removeMask(); if (this.close) { Event.purgeElement(this.close); } Panel.superclass.destroy.call(this, shallowPurge); }, /** * Forces the underlay element to be repainted through the application/removal * of a yui-force-redraw class to the underlay element. * * @method forceUnderlayRedraw */ forceUnderlayRedraw : function () { var u = this.underlay; Dom.addClass(u, "yui-force-redraw"); setTimeout(function(){Dom.removeClass(u, "yui-force-redraw");}, 0); }, /** * Returns a String representation of the object. * @method toString * @return {String} The string representation of the Panel. */ toString: function () { return "Panel " + this.id; } }); }()); (function () { /** * <p> * Dialog is an implementation of Panel that can be used to submit form * data. * </p> * <p> * Built-in functionality for buttons with event handlers is included. * If the optional YUI Button dependancy is included on the page, the buttons * created will be instances of YAHOO.widget.Button, otherwise regular HTML buttons * will be created. * </p> * <p> * Forms can be processed in 3 ways -- via an asynchronous Connection utility call, * a simple form POST or GET, or manually. The YUI Connection utility should be * included if you're using the default "async" postmethod, but is not required if * you're using any of the other postmethod values. * </p> * @namespace YAHOO.widget * @class Dialog * @extends YAHOO.widget.Panel * @constructor * @param {String} el The element ID representing the Dialog <em>OR</em> * @param {HTMLElement} el The element representing the Dialog * @param {Object} userConfig The configuration object literal containing * the configuration that should be set for this Dialog. See configuration * documentation for more details. */ YAHOO.widget.Dialog = function (el, userConfig) { YAHOO.widget.Dialog.superclass.constructor.call(this, el, userConfig); }; var Event = YAHOO.util.Event, CustomEvent = YAHOO.util.CustomEvent, Dom = YAHOO.util.Dom, Dialog = YAHOO.widget.Dialog, Lang = YAHOO.lang, /** * Constant representing the name of the Dialog's events * @property EVENT_TYPES * @private * @final * @type Object */ EVENT_TYPES = { "BEFORE_SUBMIT": "beforeSubmit", "SUBMIT": "submit", "MANUAL_SUBMIT": "manualSubmit", "ASYNC_SUBMIT": "asyncSubmit", "FORM_SUBMIT": "formSubmit", "CANCEL": "cancel" }, /** * Constant representing the Dialog's configuration properties * @property DEFAULT_CONFIG * @private * @final * @type Object */ DEFAULT_CONFIG = { "POST_METHOD": { key: "postmethod", value: "async" }, "POST_DATA" : { key: "postdata", value: null }, "BUTTONS": { key: "buttons", value: "none", supercedes: ["visible"] }, "HIDEAFTERSUBMIT" : { key: "hideaftersubmit", value: true } }; /** * Constant representing the default CSS class used for a Dialog * @property YAHOO.widget.Dialog.CSS_DIALOG * @static * @final * @type String */ Dialog.CSS_DIALOG = "yui-dialog"; function removeButtonEventHandlers() { var aButtons = this._aButtons, nButtons, oButton, i; if (Lang.isArray(aButtons)) { nButtons = aButtons.length; if (nButtons > 0) { i = nButtons - 1; do { oButton = aButtons[i]; if (YAHOO.widget.Button && oButton instanceof YAHOO.widget.Button) { oButton.destroy(); } else if (oButton.tagName.toUpperCase() == "BUTTON") { Event.purgeElement(oButton); Event.purgeElement(oButton, false); } } while (i--); } } } YAHOO.extend(Dialog, YAHOO.widget.Panel, { /** * @property form * @description Object reference to the Dialog's * <code>&#60;form&#62;</code> element. * @default null * @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/ * level-one-html.html#ID-40002357">HTMLFormElement</a> */ form: null, /** * Initializes the class's configurable properties which can be changed * using the Dialog's Config object (cfg). * @method initDefaultConfig */ initDefaultConfig: function () { Dialog.superclass.initDefaultConfig.call(this); /** * The internally maintained callback object for use with the * Connection utility. The format of the callback object is * similar to Connection Manager's callback object and is * simply passed through to Connection Manager when the async * request is made. * @property callback * @type Object */ this.callback = { /** * The function to execute upon success of the * Connection submission (when the form does not * contain a file input element). * * @property callback.success * @type Function */ success: null, /** * The function to execute upon failure of the * Connection submission * @property callback.failure * @type Function */ failure: null, /** *<p> * The function to execute upon success of the * Connection submission, when the form contains * a file input element. * </p> * <p> * <em>NOTE:</em> Connection manager will not * invoke the success or failure handlers for the file * upload use case. This will be the only callback * handler invoked. * </p> * <p> * For more information, see the <a href="http://developer.yahoo.com/yui/connection/#file"> * Connection Manager documenation on file uploads</a>. * </p> * @property callback.upload * @type Function */ /** * The arbitrary argument or arguments to pass to the Connection * callback functions * @property callback.argument * @type Object */ argument: null }; // Add form dialog config properties // /** * The method to use for posting the Dialog's form. Possible values * are "async", "form", and "manual". * @config postmethod * @type String * @default async */ this.cfg.addProperty(DEFAULT_CONFIG.POST_METHOD.key, { handler: this.configPostMethod, value: DEFAULT_CONFIG.POST_METHOD.value, validator: function (val) { if (val != "form" && val != "async" && val != "none" && val != "manual") { return false; } else { return true; } } }); /** * Any additional post data which needs to be sent when using the * <a href="#config_postmethod">async</a> postmethod for dialog POST submissions. * The format for the post data string is defined by Connection Manager's * <a href="YAHOO.util.Connect.html#method_asyncRequest">asyncRequest</a> * method. * @config postdata * @type String * @default null */ this.cfg.addProperty(DEFAULT_CONFIG.POST_DATA.key, { value: DEFAULT_CONFIG.POST_DATA.value }); /** * This property is used to configure whether or not the * dialog should be automatically hidden after submit. * * @config hideaftersubmit * @type Boolean * @default true */ this.cfg.addProperty(DEFAULT_CONFIG.HIDEAFTERSUBMIT.key, { value: DEFAULT_CONFIG.HIDEAFTERSUBMIT.value }); /** * Array of object literals, each containing a set of properties * defining a button to be appended into the Dialog's footer. * * <p>Each button object in the buttons array can have three properties:</p> * <dl> * <dt>text:</dt> * <dd> * The text that will display on the face of the button. The text can * include HTML, as long as it is compliant with HTML Button specifications. The text is added to the DOM as HTML, * and should be escaped by the implementor if coming from an external source. * </dd> * <dt>handler:</dt> * <dd>Can be either: * <ol> * <li>A reference to a function that should fire when the * button is clicked. (In this case scope of this function is * always its Dialog instance.)</li> * * <li>An object literal representing the code to be * executed when the button is clicked. * * <p>Format:</p> * * <p> * <code>{ * <br> * <strong>fn:</strong> Function, &#47;&#47; * The handler to call when the event fires. * <br> * <strong>obj:</strong> Object, &#47;&#47; * An object to pass back to the handler. * <br> * <strong>scope:</strong> Object &#47;&#47; * The object to use for the scope of the handler. * <br> * }</code> * </p> * </li> * </ol> * </dd> * <dt>isDefault:</dt> * <dd> * An optional boolean value that specifies that a button * should be highlighted and focused by default. * </dd> * </dl> * * <em>NOTE:</em>If the YUI Button Widget is included on the page, * the buttons created will be instances of YAHOO.widget.Button. * Otherwise, HTML Buttons (<code>&#60;BUTTON&#62;</code>) will be * created. * * @config buttons * @type {Array|String} * @default "none" */ this.cfg.addProperty(DEFAULT_CONFIG.BUTTONS.key, { handler: this.configButtons, value: DEFAULT_CONFIG.BUTTONS.value, supercedes : DEFAULT_CONFIG.BUTTONS.supercedes }); }, /** * Initializes the custom events for Dialog which are fired * automatically at appropriate times by the Dialog class. * @method initEvents */ initEvents: function () { Dialog.superclass.initEvents.call(this); var SIGNATURE = CustomEvent.LIST; /** * CustomEvent fired prior to submission * @event beforeSubmitEvent */ this.beforeSubmitEvent = this.createEvent(EVENT_TYPES.BEFORE_SUBMIT); this.beforeSubmitEvent.signature = SIGNATURE; /** * CustomEvent fired after submission * @event submitEvent */ this.submitEvent = this.createEvent(EVENT_TYPES.SUBMIT); this.submitEvent.signature = SIGNATURE; /** * CustomEvent fired for manual submission, before the generic submit event is fired * @event manualSubmitEvent */ this.manualSubmitEvent = this.createEvent(EVENT_TYPES.MANUAL_SUBMIT); this.manualSubmitEvent.signature = SIGNATURE; /** * CustomEvent fired after asynchronous submission, before the generic submit event is fired * * @event asyncSubmitEvent * @param {Object} conn The connection object, returned by YAHOO.util.Connect.asyncRequest */ this.asyncSubmitEvent = this.createEvent(EVENT_TYPES.ASYNC_SUBMIT); this.asyncSubmitEvent.signature = SIGNATURE; /** * CustomEvent fired after form-based submission, before the generic submit event is fired * @event formSubmitEvent */ this.formSubmitEvent = this.createEvent(EVENT_TYPES.FORM_SUBMIT); this.formSubmitEvent.signature = SIGNATURE; /** * CustomEvent fired after cancel * @event cancelEvent */ this.cancelEvent = this.createEvent(EVENT_TYPES.CANCEL); this.cancelEvent.signature = SIGNATURE; }, /** * The Dialog initialization method, which is executed for Dialog and * all of its subclasses. This method is automatically called by the * constructor, and sets up all DOM references for pre-existing markup, * and creates required markup if it is not already present. * * @method init * @param {String} el The element ID representing the Dialog <em>OR</em> * @param {HTMLElement} el The element representing the Dialog * @param {Object} userConfig The configuration object literal * containing the configuration that should be set for this Dialog. * See configuration documentation for more details. */ init: function (el, userConfig) { /* Note that we don't pass the user config in here yet because we only want it executed once, at the lowest subclass level */ Dialog.superclass.init.call(this, el/*, userConfig*/); this.beforeInitEvent.fire(Dialog); Dom.addClass(this.element, Dialog.CSS_DIALOG); this.cfg.setProperty("visible", false); if (userConfig) { this.cfg.applyConfig(userConfig, true); } //this.showEvent.subscribe(this.focusFirst, this, true); this.beforeHideEvent.subscribe(this.blurButtons, this, true); this.subscribe("changeBody", this.registerForm); this.initEvent.fire(Dialog); }, /** * Submits the Dialog's form depending on the value of the * "postmethod" configuration property. <strong>Please note: * </strong> As of version 2.3 this method will automatically handle * asyncronous file uploads should the Dialog instance's form contain * <code>&#60;input type="file"&#62;</code> elements. If a Dialog * instance will be handling asyncronous file uploads, its * <code>callback</code> property will need to be setup with a * <code>upload</code> handler rather than the standard * <code>success</code> and, or <code>failure</code> handlers. For more * information, see the <a href="http://developer.yahoo.com/yui/ * connection/#file">Connection Manager documenation on file uploads</a>. * @method doSubmit */ doSubmit: function () { var Connect = YAHOO.util.Connect, oForm = this.form, bUseFileUpload = false, bUseSecureFileUpload = false, aElements, nElements, i, formAttrs; switch (this.cfg.getProperty("postmethod")) { case "async": aElements = oForm.elements; nElements = aElements.length; if (nElements > 0) { i = nElements - 1; do { if (aElements[i].type == "file") { bUseFileUpload = true; break; } } while(i--); } if (bUseFileUpload && YAHOO.env.ua.ie && this.isSecure) { bUseSecureFileUpload = true; } formAttrs = this._getFormAttributes(oForm); Connect.setForm(oForm, bUseFileUpload, bUseSecureFileUpload); var postData = this.cfg.getProperty("postdata"); var c = Connect.asyncRequest(formAttrs.method, formAttrs.action, this.callback, postData); this.asyncSubmitEvent.fire(c); break; case "form": oForm.submit(); this.formSubmitEvent.fire(); break; case "none": case "manual": this.manualSubmitEvent.fire(); break; } }, /** * Retrieves important attributes (currently method and action) from * the form element, accounting for any elements which may have the same name * as the attributes. Defaults to "POST" and "" for method and action respectively * if the attribute cannot be retrieved. * * @method _getFormAttributes * @protected * @param {HTMLFormElement} oForm The HTML Form element from which to retrieve the attributes * @return {Object} Object literal, with method and action String properties. */ _getFormAttributes : function(oForm){ var attrs = { method : null, action : null }; if (oForm) { if (oForm.getAttributeNode) { var action = oForm.getAttributeNode("action"); var method = oForm.getAttributeNode("method"); if (action) { attrs.action = action.value; } if (method) { attrs.method = method.value; } } else { attrs.action = oForm.getAttribute("action"); attrs.method = oForm.getAttribute("method"); } } attrs.method = (Lang.isString(attrs.method) ? attrs.method : "POST").toUpperCase(); attrs.action = Lang.isString(attrs.action) ? attrs.action : ""; return attrs; }, /** * Prepares the Dialog's internal FORM object, creating one if one is * not currently present. * @method registerForm */ registerForm: function() { var form = this.element.getElementsByTagName("form")[0]; if (this.form) { if (this.form == form && Dom.isAncestor(this.element, this.form)) { return; } else { Event.purgeElement(this.form); this.form = null; } } if (!form) { form = document.createElement("form"); form.name = "frm_" + this.id; this.body.appendChild(form); } if (form) { this.form = form; Event.on(form, "submit", this._submitHandler, this, true); } }, /** * Internal handler for the form submit event * * @method _submitHandler * @protected * @param {DOMEvent} e The DOM Event object */ _submitHandler : function(e) { Event.stopEvent(e); this.submit(); this.form.blur(); }, /** * Sets up a tab, shift-tab loop between the first and last elements * provided. NOTE: Sets up the preventBackTab and preventTabOut KeyListener * instance properties, which are reset everytime this method is invoked. * * @method setTabLoop * @param {HTMLElement} firstElement * @param {HTMLElement} lastElement * */ setTabLoop : function(firstElement, lastElement) { firstElement = firstElement || this.firstButton; lastElement = lastElement || this.lastButton; Dialog.superclass.setTabLoop.call(this, firstElement, lastElement); }, /** * Protected internal method for setTabLoop, which can be used by * subclasses to jump in and modify the arguments passed in if required. * * @method _setTabLoop * @param {HTMLElement} firstElement * @param {HTMLElement} lastElement * @protected */ _setTabLoop : function(firstElement, lastElement) { firstElement = firstElement || this.firstButton; lastElement = this.lastButton || lastElement; this.setTabLoop(firstElement, lastElement); }, /** * Configures instance properties, pointing to the * first and last focusable elements in the Dialog's form. * * @method setFirstLastFocusable */ setFirstLastFocusable : function() { Dialog.superclass.setFirstLastFocusable.call(this); var i, l, el, elements = this.focusableElements; this.firstFormElement = null; this.lastFormElement = null; if (this.form && elements && elements.length > 0) { l = elements.length; for (i = 0; i < l; ++i) { el = elements[i]; if (this.form === el.form) { this.firstFormElement = el; break; } } for (i = l-1; i >= 0; --i) { el = elements[i]; if (this.form === el.form) { this.lastFormElement = el; break; } } } }, // BEGIN BUILT-IN PROPERTY EVENT HANDLERS // /** * The default event handler fired when the "close" property is * changed. The method controls the appending or hiding of the close * icon at the top right of the Dialog. * @method configClose * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For * configuration handlers, args[0] will equal the newly applied value * for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configClose: function (type, args, obj) { Dialog.superclass.configClose.apply(this, arguments); }, /** * Event handler for the close icon * * @method _doClose * @protected * * @param {DOMEvent} e */ _doClose : function(e) { Event.preventDefault(e); this.cancel(); }, /** * The default event handler for the "buttons" configuration property * @method configButtons * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configButtons: function (type, args, obj) { var Button = YAHOO.widget.Button, aButtons = args[0], oInnerElement = this.innerElement, oButton, oButtonEl, oYUIButton, nButtons, oSpan, oFooter, i; removeButtonEventHandlers.call(this); this._aButtons = null; if (Lang.isArray(aButtons)) { oSpan = document.createElement("span"); oSpan.className = "button-group"; nButtons = aButtons.length; this._aButtons = []; this.defaultHtmlButton = null; for (i = 0; i < nButtons; i++) { oButton = aButtons[i]; if (Button) { oYUIButton = new Button({ label: oButton.text, type:oButton.type }); oYUIButton.appendTo(oSpan); oButtonEl = oYUIButton.get("element"); if (oButton.isDefault) { oYUIButton.addClass("default"); this.defaultHtmlButton = oButtonEl; } if (Lang.isFunction(oButton.handler)) { oYUIButton.set("onclick", { fn: oButton.handler, obj: this, scope: this }); } else if (Lang.isObject(oButton.handler) && Lang.isFunction(oButton.handler.fn)) { oYUIButton.set("onclick", { fn: oButton.handler.fn, obj: ((!Lang.isUndefined(oButton.handler.obj)) ? oButton.handler.obj : this), scope: (oButton.handler.scope || this) }); } this._aButtons[this._aButtons.length] = oYUIButton; } else { oButtonEl = document.createElement("button"); oButtonEl.setAttribute("type", "button"); if (oButton.isDefault) { oButtonEl.className = "default"; this.defaultHtmlButton = oButtonEl; } oButtonEl.innerHTML = oButton.text; if (Lang.isFunction(oButton.handler)) { Event.on(oButtonEl, "click", oButton.handler, this, true); } else if (Lang.isObject(oButton.handler) && Lang.isFunction(oButton.handler.fn)) { Event.on(oButtonEl, "click", oButton.handler.fn, ((!Lang.isUndefined(oButton.handler.obj)) ? oButton.handler.obj : this), (oButton.handler.scope || this)); } oSpan.appendChild(oButtonEl); this._aButtons[this._aButtons.length] = oButtonEl; } oButton.htmlButton = oButtonEl; if (i === 0) { this.firstButton = oButtonEl; } if (i == (nButtons - 1)) { this.lastButton = oButtonEl; } } this.setFooter(oSpan); oFooter = this.footer; if (Dom.inDocument(this.element) && !Dom.isAncestor(oInnerElement, oFooter)) { oInnerElement.appendChild(oFooter); } this.buttonSpan = oSpan; } else { // Do cleanup oSpan = this.buttonSpan; oFooter = this.footer; if (oSpan && oFooter) { oFooter.removeChild(oSpan); this.buttonSpan = null; this.firstButton = null; this.lastButton = null; this.defaultHtmlButton = null; } } this.changeContentEvent.fire(); }, /** * @method getButtons * @description Returns an array containing each of the Dialog's * buttons, by default an array of HTML <code>&#60;BUTTON&#62;</code> * elements. If the Dialog's buttons were created using the * YAHOO.widget.Button class (via the inclusion of the optional Button * dependency on the page), an array of YAHOO.widget.Button instances * is returned. * @return {Array} */ getButtons: function () { return this._aButtons || null; }, /** * <p> * Sets focus to the first focusable element in the Dialog's form if found, * else, the default button if found, else the first button defined via the * "buttons" configuration property. * </p> * <p> * This method is invoked when the Dialog is made visible. * </p> * @method focusFirst * @return {Boolean} true, if focused. false if not */ focusFirst: function (type, args, obj) { var el = this.firstFormElement, focused = false; if (args && args[1]) { Event.stopEvent(args[1]); // When tabbing here, use firstElement instead of firstFormElement if (args[0] === 9 && this.firstElement) { el = this.firstElement; } } if (el) { try { el.focus(); focused = true; } catch(oException) { // Ignore } } else { if (this.defaultHtmlButton) { focused = this.focusDefaultButton(); } else { focused = this.focusFirstButton(); } } return focused; }, /** * Sets focus to the last element in the Dialog's form or the last * button defined via the "buttons" configuration property. * @method focusLast * @return {Boolean} true, if focused. false if not */ focusLast: function (type, args, obj) { var aButtons = this.cfg.getProperty("buttons"), el = this.lastFormElement, focused = false; if (args && args[1]) { Event.stopEvent(args[1]); // When tabbing here, use lastElement instead of lastFormElement if (args[0] === 9 && this.lastElement) { el = this.lastElement; } } if (aButtons && Lang.isArray(aButtons)) { focused = this.focusLastButton(); } else { if (el) { try { el.focus(); focused = true; } catch(oException) { // Ignore } } } return focused; }, /** * Helper method to normalize button references. It either returns the * YUI Button instance for the given element if found, * or the passes back the HTMLElement reference if a corresponding YUI Button * reference is not found or YAHOO.widget.Button does not exist on the page. * * @method _getButton * @private * @param {HTMLElement} button * @return {YAHOO.widget.Button|HTMLElement} */ _getButton : function(button) { var Button = YAHOO.widget.Button; // If we have an HTML button and YUI Button is on the page, // get the YUI Button reference if available. if (Button && button && button.nodeName && button.id) { button = Button.getButton(button.id) || button; } return button; }, /** * Sets the focus to the button that is designated as the default via * the "buttons" configuration property. By default, this method is * called when the Dialog is made visible. * @method focusDefaultButton * @return {Boolean} true if focused, false if not */ focusDefaultButton: function () { var button = this._getButton(this.defaultHtmlButton), focused = false; if (button) { /* Place the call to the "focus" method inside a try/catch block to prevent IE from throwing JavaScript errors if the element is disabled or hidden. */ try { button.focus(); focused = true; } catch(oException) { } } return focused; }, /** * Blurs all the buttons defined via the "buttons" * configuration property. * @method blurButtons */ blurButtons: function () { var aButtons = this.cfg.getProperty("buttons"), nButtons, oButton, oElement, i; if (aButtons && Lang.isArray(aButtons)) { nButtons = aButtons.length; if (nButtons > 0) { i = (nButtons - 1); do { oButton = aButtons[i]; if (oButton) { oElement = this._getButton(oButton.htmlButton); if (oElement) { /* Place the call to the "blur" method inside a try/catch block to prevent IE from throwing JavaScript errors if the element is disabled or hidden. */ try { oElement.blur(); } catch(oException) { // ignore } } } } while(i--); } } }, /** * Sets the focus to the first button created via the "buttons" * configuration property. * @method focusFirstButton * @return {Boolean} true, if focused. false if not */ focusFirstButton: function () { var aButtons = this.cfg.getProperty("buttons"), oButton, oElement, focused = false; if (aButtons && Lang.isArray(aButtons)) { oButton = aButtons[0]; if (oButton) { oElement = this._getButton(oButton.htmlButton); if (oElement) { /* Place the call to the "focus" method inside a try/catch block to prevent IE from throwing JavaScript errors if the element is disabled or hidden. */ try { oElement.focus(); focused = true; } catch(oException) { // ignore } } } } return focused; }, /** * Sets the focus to the last button created via the "buttons" * configuration property. * @method focusLastButton * @return {Boolean} true, if focused. false if not */ focusLastButton: function () { var aButtons = this.cfg.getProperty("buttons"), nButtons, oButton, oElement, focused = false; if (aButtons && Lang.isArray(aButtons)) { nButtons = aButtons.length; if (nButtons > 0) { oButton = aButtons[(nButtons - 1)]; if (oButton) { oElement = this._getButton(oButton.htmlButton); if (oElement) { /* Place the call to the "focus" method inside a try/catch block to prevent IE from throwing JavaScript errors if the element is disabled or hidden. */ try { oElement.focus(); focused = true; } catch(oException) { // Ignore } } } } } return focused; }, /** * The default event handler for the "postmethod" configuration property * @method configPostMethod * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For * configuration handlers, args[0] will equal the newly applied value * for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configPostMethod: function (type, args, obj) { this.registerForm(); }, // END BUILT-IN PROPERTY EVENT HANDLERS // /** * Built-in function hook for writing a validation function that will * be checked for a "true" value prior to a submit. This function, as * implemented by default, always returns true, so it should be * overridden if validation is necessary. * @method validate */ validate: function () { return true; }, /** * Executes a submit of the Dialog if validation * is successful. By default the Dialog is hidden * after submission, but you can set the "hideaftersubmit" * configuration property to false, to prevent the Dialog * from being hidden. * * @method submit */ submit: function () { if (this.validate()) { if (this.beforeSubmitEvent.fire()) { this.doSubmit(); this.submitEvent.fire(); if (this.cfg.getProperty("hideaftersubmit")) { this.hide(); } return true; } else { return false; } } else { return false; } }, /** * Executes the cancel of the Dialog followed by a hide. * @method cancel */ cancel: function () { this.cancelEvent.fire(); this.hide(); }, /** * Returns a JSON-compatible data structure representing the data * currently contained in the form. * @method getData * @return {Object} A JSON object reprsenting the data of the * current form. */ getData: function () { var oForm = this.form, aElements, nTotalElements, oData, sName, oElement, nElements, sType, sTagName, aOptions, nOptions, aValues, oOption, oRadio, oCheckbox, valueAttr, i, n; function isFormElement(p_oElement) { var sTag = p_oElement.tagName.toUpperCase(); return ((sTag == "INPUT" || sTag == "TEXTAREA" || sTag == "SELECT") && p_oElement.name == sName); } if (oForm) { aElements = oForm.elements; nTotalElements = aElements.length; oData = {}; for (i = 0; i < nTotalElements; i++) { sName = aElements[i].name; /* Using "Dom.getElementsBy" to safeguard user from JS errors that result from giving a form field (or set of fields) the same name as a native method of a form (like "submit") or a DOM collection (such as the "item" method). Originally tried accessing fields via the "namedItem" method of the "element" collection, but discovered that it won't return a collection of fields in Gecko. */ oElement = Dom.getElementsBy(isFormElement, "*", oForm); nElements = oElement.length; if (nElements > 0) { if (nElements == 1) { oElement = oElement[0]; sType = oElement.type; sTagName = oElement.tagName.toUpperCase(); switch (sTagName) { case "INPUT": if (sType == "checkbox") { oData[sName] = oElement.checked; } else if (sType != "radio") { oData[sName] = oElement.value; } break; case "TEXTAREA": oData[sName] = oElement.value; break; case "SELECT": aOptions = oElement.options; nOptions = aOptions.length; aValues = []; for (n = 0; n < nOptions; n++) { oOption = aOptions[n]; if (oOption.selected) { valueAttr = oOption.attributes.value; aValues[aValues.length] = (valueAttr && valueAttr.specified) ? oOption.value : oOption.text; } } oData[sName] = aValues; break; } } else { sType = oElement[0].type; switch (sType) { case "radio": for (n = 0; n < nElements; n++) { oRadio = oElement[n]; if (oRadio.checked) { oData[sName] = oRadio.value; break; } } break; case "checkbox": aValues = []; for (n = 0; n < nElements; n++) { oCheckbox = oElement[n]; if (oCheckbox.checked) { aValues[aValues.length] = oCheckbox.value; } } oData[sName] = aValues; break; } } } } } return oData; }, /** * Removes the Panel element from the DOM and sets all child elements * to null. * @method destroy * @param {boolean} shallowPurge If true, only the parent element's DOM event listeners are purged. If false, or not provided, all children are also purged of DOM event listeners. * NOTE: The flag is a "shallowPurge" flag, as opposed to what may be a more intuitive "purgeChildren" flag to maintain backwards compatibility with behavior prior to 2.9.0. */ destroy: function (shallowPurge) { removeButtonEventHandlers.call(this); this._aButtons = null; var aForms = this.element.getElementsByTagName("form"), oForm; if (aForms.length > 0) { oForm = aForms[0]; if (oForm) { Event.purgeElement(oForm); if (oForm.parentNode) { oForm.parentNode.removeChild(oForm); } this.form = null; } } Dialog.superclass.destroy.call(this, shallowPurge); }, /** * Returns a string representation of the object. * @method toString * @return {String} The string representation of the Dialog */ toString: function () { return "Dialog " + this.id; } }); }()); (function () { /** * SimpleDialog is a simple implementation of Dialog that can be used to * submit a single value. Forms can be processed in 3 ways -- via an * asynchronous Connection utility call, a simple form POST or GET, * or manually. * @namespace YAHOO.widget * @class SimpleDialog * @extends YAHOO.widget.Dialog * @constructor * @param {String} el The element ID representing the SimpleDialog * <em>OR</em> * @param {HTMLElement} el The element representing the SimpleDialog * @param {Object} userConfig The configuration object literal containing * the configuration that should be set for this SimpleDialog. See * configuration documentation for more details. */ YAHOO.widget.SimpleDialog = function (el, userConfig) { YAHOO.widget.SimpleDialog.superclass.constructor.call(this, el, userConfig); }; var Dom = YAHOO.util.Dom, SimpleDialog = YAHOO.widget.SimpleDialog, /** * Constant representing the SimpleDialog's configuration properties * @property DEFAULT_CONFIG * @private * @final * @type Object */ DEFAULT_CONFIG = { "ICON": { key: "icon", value: "none", suppressEvent: true }, "TEXT": { key: "text", value: "", suppressEvent: true, supercedes: ["icon"] } }; /** * Constant for the standard network icon for a blocking action * @property YAHOO.widget.SimpleDialog.ICON_BLOCK * @static * @final * @type String */ SimpleDialog.ICON_BLOCK = "blckicon"; /** * Constant for the standard network icon for alarm * @property YAHOO.widget.SimpleDialog.ICON_ALARM * @static * @final * @type String */ SimpleDialog.ICON_ALARM = "alrticon"; /** * Constant for the standard network icon for help * @property YAHOO.widget.SimpleDialog.ICON_HELP * @static * @final * @type String */ SimpleDialog.ICON_HELP = "hlpicon"; /** * Constant for the standard network icon for info * @property YAHOO.widget.SimpleDialog.ICON_INFO * @static * @final * @type String */ SimpleDialog.ICON_INFO = "infoicon"; /** * Constant for the standard network icon for warn * @property YAHOO.widget.SimpleDialog.ICON_WARN * @static * @final * @type String */ SimpleDialog.ICON_WARN = "warnicon"; /** * Constant for the standard network icon for a tip * @property YAHOO.widget.SimpleDialog.ICON_TIP * @static * @final * @type String */ SimpleDialog.ICON_TIP = "tipicon"; /** * Constant representing the name of the CSS class applied to the element * created by the "icon" configuration property. * @property YAHOO.widget.SimpleDialog.ICON_CSS_CLASSNAME * @static * @final * @type String */ SimpleDialog.ICON_CSS_CLASSNAME = "yui-icon"; /** * Constant representing the default CSS class used for a SimpleDialog * @property YAHOO.widget.SimpleDialog.CSS_SIMPLEDIALOG * @static * @final * @type String */ SimpleDialog.CSS_SIMPLEDIALOG = "yui-simple-dialog"; YAHOO.extend(SimpleDialog, YAHOO.widget.Dialog, { /** * Initializes the class's configurable properties which can be changed * using the SimpleDialog's Config object (cfg). * @method initDefaultConfig */ initDefaultConfig: function () { SimpleDialog.superclass.initDefaultConfig.call(this); // Add dialog config properties // /** * Sets the informational icon for the SimpleDialog * @config icon * @type String * @default "none" */ this.cfg.addProperty(DEFAULT_CONFIG.ICON.key, { handler: this.configIcon, value: DEFAULT_CONFIG.ICON.value, suppressEvent: DEFAULT_CONFIG.ICON.suppressEvent }); /** * Sets the text for the SimpleDialog. The text is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source. * @config text * @type HTML * @default "" */ this.cfg.addProperty(DEFAULT_CONFIG.TEXT.key, { handler: this.configText, value: DEFAULT_CONFIG.TEXT.value, suppressEvent: DEFAULT_CONFIG.TEXT.suppressEvent, supercedes: DEFAULT_CONFIG.TEXT.supercedes }); }, /** * The SimpleDialog initialization method, which is executed for * SimpleDialog and all of its subclasses. This method is automatically * called by the constructor, and sets up all DOM references for * pre-existing markup, and creates required markup if it is not * already present. * @method init * @param {String} el The element ID representing the SimpleDialog * <em>OR</em> * @param {HTMLElement} el The element representing the SimpleDialog * @param {Object} userConfig The configuration object literal * containing the configuration that should be set for this * SimpleDialog. See configuration documentation for more details. */ init: function (el, userConfig) { /* Note that we don't pass the user config in here yet because we only want it executed once, at the lowest subclass level */ SimpleDialog.superclass.init.call(this, el/*, userConfig*/); this.beforeInitEvent.fire(SimpleDialog); Dom.addClass(this.element, SimpleDialog.CSS_SIMPLEDIALOG); this.cfg.queueProperty("postmethod", "manual"); if (userConfig) { this.cfg.applyConfig(userConfig, true); } this.beforeRenderEvent.subscribe(function () { if (! this.body) { this.setBody(""); } }, this, true); this.initEvent.fire(SimpleDialog); }, /** * Prepares the SimpleDialog's internal FORM object, creating one if one * is not currently present, and adding the value hidden field. * @method registerForm */ registerForm: function () { SimpleDialog.superclass.registerForm.call(this); var doc = this.form.ownerDocument, input = doc.createElement("input"); input.type = "hidden"; input.name = this.id; input.value = ""; this.form.appendChild(input); }, // BEGIN BUILT-IN PROPERTY EVENT HANDLERS // /** * Fired when the "icon" property is set. * @method configIcon * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configIcon: function (type,args,obj) { var sIcon = args[0], oBody = this.body, sCSSClass = SimpleDialog.ICON_CSS_CLASSNAME, aElements, oIcon, oIconParent; if (sIcon && sIcon != "none") { aElements = Dom.getElementsByClassName(sCSSClass, "*" , oBody); if (aElements.length === 1) { oIcon = aElements[0]; oIconParent = oIcon.parentNode; if (oIconParent) { oIconParent.removeChild(oIcon); oIcon = null; } } if (sIcon.indexOf(".") == -1) { oIcon = document.createElement("span"); oIcon.className = (sCSSClass + " " + sIcon); oIcon.innerHTML = "&#160;"; } else { oIcon = document.createElement("img"); oIcon.src = (this.imageRoot + sIcon); oIcon.className = sCSSClass; } if (oIcon) { oBody.insertBefore(oIcon, oBody.firstChild); } } }, /** * Fired when the "text" property is set. * @method configText * @param {String} type The CustomEvent type (usually the property name) * @param {Object[]} args The CustomEvent arguments. For configuration * handlers, args[0] will equal the newly applied value for the property. * @param {Object} obj The scope object. For configuration handlers, * this will usually equal the owner. */ configText: function (type,args,obj) { var text = args[0]; if (text) { this.setBody(text); this.cfg.refireEvent("icon"); } }, // END BUILT-IN PROPERTY EVENT HANDLERS // /** * Returns a string representation of the object. * @method toString * @return {String} The string representation of the SimpleDialog */ toString: function () { return "SimpleDialog " + this.id; } /** * <p> * Sets the SimpleDialog's body content to the HTML specified. * If no body is present, one will be automatically created. * An empty string can be passed to the method to clear the contents of the body. * </p> * <p><strong>NOTE:</strong> SimpleDialog provides the <a href="#config_text">text</a> * and <a href="#config_icon">icon</a> configuration properties to set the contents * of it's body element in accordance with the UI design for a SimpleDialog (an * icon and message text). Calling setBody on the SimpleDialog will not enforce this * UI design constraint and will replace the entire contents of the SimpleDialog body. * It should only be used if you wish the replace the default icon/text body structure * of a SimpleDialog with your own custom markup.</p> * * @method setBody * @param {HTML} bodyContent The HTML used to set the body. * As a convenience, non HTMLElement objects can also be passed into * the method, and will be treated as strings, with the body innerHTML * set to their default toString implementations. * * <p>NOTE: Markup passed into this method is added to the DOM as HTML, and should be escaped by the implementor if coming from an external source.</p> * * <em>OR</em> * @param {HTMLElement} bodyContent The HTMLElement to add as the first and only child of the body element. * <em>OR</em> * @param {DocumentFragment} bodyContent The document fragment * containing elements which are to be added to the body */ }); }()); (function () { /** * ContainerEffect encapsulates animation transitions that are executed when * an Overlay is shown or hidden. * @namespace YAHOO.widget * @class ContainerEffect * @constructor * @param {YAHOO.widget.Overlay} overlay The Overlay that the animation * should be associated with * @param {Object} attrIn The object literal representing the animation * arguments to be used for the animate-in transition. The arguments for * this literal are: attributes(object, see YAHOO.util.Anim for description), * duration(Number), and method(i.e. Easing.easeIn). * @param {Object} attrOut The object literal representing the animation * arguments to be used for the animate-out transition. The arguments for * this literal are: attributes(object, see YAHOO.util.Anim for description), * duration(Number), and method(i.e. Easing.easeIn). * @param {HTMLElement} targetElement Optional. The target element that * should be animated during the transition. Defaults to overlay.element. * @param {class} Optional. The animation class to instantiate. Defaults to * YAHOO.util.Anim. Other options include YAHOO.util.Motion. */ YAHOO.widget.ContainerEffect = function (overlay, attrIn, attrOut, targetElement, animClass) { if (!animClass) { animClass = YAHOO.util.Anim; } /** * The overlay to animate * @property overlay * @type YAHOO.widget.Overlay */ this.overlay = overlay; /** * The animation attributes to use when transitioning into view * @property attrIn * @type Object */ this.attrIn = attrIn; /** * The animation attributes to use when transitioning out of view * @property attrOut * @type Object */ this.attrOut = attrOut; /** * The target element to be animated * @property targetElement * @type HTMLElement */ this.targetElement = targetElement || overlay.element; /** * The animation class to use for animating the overlay * @property animClass * @type class */ this.animClass = animClass; }; var Dom = YAHOO.util.Dom, CustomEvent = YAHOO.util.CustomEvent, ContainerEffect = YAHOO.widget.ContainerEffect; /** * A pre-configured ContainerEffect instance that can be used for fading * an overlay in and out. * @method FADE * @static * @param {YAHOO.widget.Overlay} overlay The Overlay object to animate * @param {Number} dur The duration of the animation * @return {YAHOO.widget.ContainerEffect} The configured ContainerEffect object */ ContainerEffect.FADE = function (overlay, dur) { var Easing = YAHOO.util.Easing, fin = { attributes: {opacity:{from:0, to:1}}, duration: dur, method: Easing.easeIn }, fout = { attributes: {opacity:{to:0}}, duration: dur, method: Easing.easeOut }, fade = new ContainerEffect(overlay, fin, fout, overlay.element); fade.handleUnderlayStart = function() { var underlay = this.overlay.underlay; if (underlay && YAHOO.env.ua.ie) { var hasFilters = (underlay.filters && underlay.filters.length > 0); if(hasFilters) { Dom.addClass(overlay.element, "yui-effect-fade"); } } }; fade.handleUnderlayComplete = function() { var underlay = this.overlay.underlay; if (underlay && YAHOO.env.ua.ie) { Dom.removeClass(overlay.element, "yui-effect-fade"); } }; fade.handleStartAnimateIn = function (type, args, obj) { obj.overlay._fadingIn = true; Dom.addClass(obj.overlay.element, "hide-select"); if (!obj.overlay.underlay) { obj.overlay.cfg.refireEvent("underlay"); } obj.handleUnderlayStart(); obj.overlay._setDomVisibility(true); Dom.setStyle(obj.overlay.element, "opacity", 0); }; fade.handleCompleteAnimateIn = function (type,args,obj) { obj.overlay._fadingIn = false; Dom.removeClass(obj.overlay.element, "hide-select"); if (obj.overlay.element.style.filter) { obj.overlay.element.style.filter = null; } obj.handleUnderlayComplete(); obj.overlay.cfg.refireEvent("iframe"); obj.animateInCompleteEvent.fire(); }; fade.handleStartAnimateOut = function (type, args, obj) { obj.overlay._fadingOut = true; Dom.addClass(obj.overlay.element, "hide-select"); obj.handleUnderlayStart(); }; fade.handleCompleteAnimateOut = function (type, args, obj) { obj.overlay._fadingOut = false; Dom.removeClass(obj.overlay.element, "hide-select"); if (obj.overlay.element.style.filter) { obj.overlay.element.style.filter = null; } obj.overlay._setDomVisibility(false); Dom.setStyle(obj.overlay.element, "opacity", 1); obj.handleUnderlayComplete(); obj.overlay.cfg.refireEvent("iframe"); obj.animateOutCompleteEvent.fire(); }; fade.init(); return fade; }; /** * A pre-configured ContainerEffect instance that can be used for sliding an * overlay in and out. * @method SLIDE * @static * @param {YAHOO.widget.Overlay} overlay The Overlay object to animate * @param {Number} dur The duration of the animation * @return {YAHOO.widget.ContainerEffect} The configured ContainerEffect object */ ContainerEffect.SLIDE = function (overlay, dur) { var Easing = YAHOO.util.Easing, x = overlay.cfg.getProperty("x") || Dom.getX(overlay.element), y = overlay.cfg.getProperty("y") || Dom.getY(overlay.element), clientWidth = Dom.getClientWidth(), offsetWidth = overlay.element.offsetWidth, sin = { attributes: { points: { to: [x, y] } }, duration: dur, method: Easing.easeIn }, sout = { attributes: { points: { to: [(clientWidth + 25), y] } }, duration: dur, method: Easing.easeOut }, slide = new ContainerEffect(overlay, sin, sout, overlay.element, YAHOO.util.Motion); slide.handleStartAnimateIn = function (type,args,obj) { obj.overlay.element.style.left = ((-25) - offsetWidth) + "px"; obj.overlay.element.style.top = y + "px"; }; slide.handleTweenAnimateIn = function (type, args, obj) { var pos = Dom.getXY(obj.overlay.element), currentX = pos[0], currentY = pos[1]; if (Dom.getStyle(obj.overlay.element, "visibility") == "hidden" && currentX < x) { obj.overlay._setDomVisibility(true); } obj.overlay.cfg.setProperty("xy", [currentX, currentY], true); obj.overlay.cfg.refireEvent("iframe"); }; slide.handleCompleteAnimateIn = function (type, args, obj) { obj.overlay.cfg.setProperty("xy", [x, y], true); obj.startX = x; obj.startY = y; obj.overlay.cfg.refireEvent("iframe"); obj.animateInCompleteEvent.fire(); }; slide.handleStartAnimateOut = function (type, args, obj) { var vw = Dom.getViewportWidth(), pos = Dom.getXY(obj.overlay.element), yso = pos[1]; obj.animOut.attributes.points.to = [(vw + 25), yso]; }; slide.handleTweenAnimateOut = function (type, args, obj) { var pos = Dom.getXY(obj.overlay.element), xto = pos[0], yto = pos[1]; obj.overlay.cfg.setProperty("xy", [xto, yto], true); obj.overlay.cfg.refireEvent("iframe"); }; slide.handleCompleteAnimateOut = function (type, args, obj) { obj.overlay._setDomVisibility(false); obj.overlay.cfg.setProperty("xy", [x, y]); obj.animateOutCompleteEvent.fire(); }; slide.init(); return slide; }; ContainerEffect.prototype = { /** * Initializes the animation classes and events. * @method init */ init: function () { this.beforeAnimateInEvent = this.createEvent("beforeAnimateIn"); this.beforeAnimateInEvent.signature = CustomEvent.LIST; this.beforeAnimateOutEvent = this.createEvent("beforeAnimateOut"); this.beforeAnimateOutEvent.signature = CustomEvent.LIST; this.animateInCompleteEvent = this.createEvent("animateInComplete"); this.animateInCompleteEvent.signature = CustomEvent.LIST; this.animateOutCompleteEvent = this.createEvent("animateOutComplete"); this.animateOutCompleteEvent.signature = CustomEvent.LIST; this.animIn = new this.animClass( this.targetElement, this.attrIn.attributes, this.attrIn.duration, this.attrIn.method); this.animIn.onStart.subscribe(this.handleStartAnimateIn, this); this.animIn.onTween.subscribe(this.handleTweenAnimateIn, this); this.animIn.onComplete.subscribe(this.handleCompleteAnimateIn,this); this.animOut = new this.animClass( this.targetElement, this.attrOut.attributes, this.attrOut.duration, this.attrOut.method); this.animOut.onStart.subscribe(this.handleStartAnimateOut, this); this.animOut.onTween.subscribe(this.handleTweenAnimateOut, this); this.animOut.onComplete.subscribe(this.handleCompleteAnimateOut, this); }, /** * Triggers the in-animation. * @method animateIn */ animateIn: function () { this._stopAnims(this.lastFrameOnStop); this.beforeAnimateInEvent.fire(); this.animIn.animate(); }, /** * Triggers the out-animation. * @method animateOut */ animateOut: function () { this._stopAnims(this.lastFrameOnStop); this.beforeAnimateOutEvent.fire(); this.animOut.animate(); }, /** * Flag to define whether Anim should jump to the last frame, * when animateIn or animateOut is stopped. * * @property lastFrameOnStop * @default true * @type boolean */ lastFrameOnStop : true, /** * Stops both animIn and animOut instances, if in progress. * * @method _stopAnims * @param {boolean} finish If true, animation will jump to final frame. * @protected */ _stopAnims : function(finish) { if (this.animOut && this.animOut.isAnimated()) { this.animOut.stop(finish); } if (this.animIn && this.animIn.isAnimated()) { this.animIn.stop(finish); } }, /** * The default onStart handler for the in-animation. * @method handleStartAnimateIn * @param {String} type The CustomEvent type * @param {Object[]} args The CustomEvent arguments * @param {Object} obj The scope object */ handleStartAnimateIn: function (type, args, obj) { }, /** * The default onTween handler for the in-animation. * @method handleTweenAnimateIn * @param {String} type The CustomEvent type * @param {Object[]} args The CustomEvent arguments * @param {Object} obj The scope object */ handleTweenAnimateIn: function (type, args, obj) { }, /** * The default onComplete handler for the in-animation. * @method handleCompleteAnimateIn * @param {String} type The CustomEvent type * @param {Object[]} args The CustomEvent arguments * @param {Object} obj The scope object */ handleCompleteAnimateIn: function (type, args, obj) { }, /** * The default onStart handler for the out-animation. * @method handleStartAnimateOut * @param {String} type The CustomEvent type * @param {Object[]} args The CustomEvent arguments * @param {Object} obj The scope object */ handleStartAnimateOut: function (type, args, obj) { }, /** * The default onTween handler for the out-animation. * @method handleTweenAnimateOut * @param {String} type The CustomEvent type * @param {Object[]} args The CustomEvent arguments * @param {Object} obj The scope object */ handleTweenAnimateOut: function (type, args, obj) { }, /** * The default onComplete handler for the out-animation. * @method handleCompleteAnimateOut * @param {String} type The CustomEvent type * @param {Object[]} args The CustomEvent arguments * @param {Object} obj The scope object */ handleCompleteAnimateOut: function (type, args, obj) { }, /** * Returns a string representation of the object. * @method toString * @return {String} The string representation of the ContainerEffect */ toString: function () { var output = "ContainerEffect"; if (this.overlay) { output += " [" + this.overlay.toString() + "]"; } return output; } }; YAHOO.lang.augmentProto(ContainerEffect, YAHOO.util.EventProvider); })(); YAHOO.register("container", YAHOO.widget.Module, {version: "2.9.0", build: "2800"}); }, '2.9.0' ,{"requires": ["yui2-yahoo", "yui2-dom", "yui2-event", "yui2-skin-sam-container"], "supersedes": ["yui2-containercore"], "optional": ["yui2-animation", "yui2-dragdrop", "yui2-connection"]});
examples/huge-apps/app.js
skevy/react-router
import React from 'react'; import { Router } from 'react-router'; import stubbedCourses from './stubs/COURSES'; var rootRoute = { component: 'div', childRoutes: [{ path: '/', component: require('./components/App'), childRoutes: [ require('./routes/Calendar'), require('./routes/Course'), require('./routes/Grades'), require('./routes/Messages'), require('./routes/Profile'), ] }] }; React.render( <Router routes={rootRoute} />, document.getElementById('example') ); // I've unrolled the recursive directory loop that is happening above to get a // better idea of just what this huge-apps Router looks like // // import { Route } from 'react-router' // import App from './components/App'; // import Course from './routes/Course/components/Course'; // import AnnouncementsSidebar from './routes/Course/routes/Announcements/components/Sidebar'; // import Announcements from './routes/Course/routes/Announcements/components/Announcements'; // import Announcement from './routes/Course/routes/Announcements/routes/Announcement/components/Announcement'; // import AssignmentsSidebar from './routes/Course/routes/Assignments/components/Sidebar'; // import Assignments from './routes/Course/routes/Assignments/components/Assignments'; // import Assignment from './routes/Course/routes/Assignments/routes/Assignment/components/Assignment'; // import CourseGrades from './routes/Course/routes/Grades/components/Grades'; // import Calendar from './routes/Calendar/components/Calendar'; // import Grades from './routes/Grades/components/Grades'; // import Messages from './routes/Messages/components/Messages'; // React.render( // <Router> // <Route path="/" component={App}> // <Route path="calendar" component={Calendar} /> // <Route path="course/:courseId" component={Course}> // <Route path="announcements" components={{ // sidebar: AnnouncementsSidebar, // main: Announcements // }}> // <Route path=":announcementId" component={Announcement} /> // </Route> // <Route path="assignments" components={{ // sidebar: AssignmentsSidebar, // main: Assignments // }}> // <Route path=":assignmentId" component={Assignment} /> // </Route> // <Route path="grades" component={CourseGrades} /> // </Route> // <Route path="grades" component={Grades} /> // <Route path="messages" component={Messages} /> // <Route path="profile" component={Calendar} /> // </Route> // </Router>, // document.getElementById('example') // );
ajax/libs/jquery/1.11.0-beta3/jquery.min.js
Piicksarn/cdnjs
/*! jQuery v1.11.0-beta3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}(this,function(a){var b=[],c=b.slice,d=b.concat,e=b.push,f=b.indexOf,g={},h=g.toString,i=g.hasOwnProperty,j="".trim,k={},l="1.11.0-beta3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return c.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:c.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(c.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:e,sort:b.sort,splice:b.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!i.call(a,"constructor")&&!i.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return i.call(a,b);for(b in a);return void 0===b||i.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?g[h.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:j&&!j.call("\ufeff\xa0")?function(a){return null==a?"":j.call(a)}:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):e.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(f)return f.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var e,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)e=b(a[f],f,c),null!=e&&i.push(e);else for(f in a)e=b(a[f],f,c),null!=e&&i.push(e);return d.apply([],i)},guid:1,proxy:function(a,b){var d,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(d=c.call(arguments,2),e=function(){return a.apply(b||this,d.concat(c.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){g["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t="sizzle"+-new Date,u=a.document,v=0,w=0,x=fb(),y=fb(),z=fb(),A=function(a,b){return a===b&&(k=!0),0},B="undefined",C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=E.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")"+L+"*(?:([*^$|!~]?=)"+L+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+N+")|)|)"+L+"*\\]",P=":("+M+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+O.replace(3,8)+")*)|.*)\\)|)",Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(P),V=new RegExp("^"+N+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,ab=/'|\\/g,bb=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),cb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{H.apply(E=I.call(u.childNodes),u.childNodes),E[u.childNodes.length].nodeType}catch(db){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function eb(a,b,d,e){var f,g,h,i,j,k,n,q,r,v;if((b?b.ownerDocument||b:u)!==m&&l(b),b=b||m,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(o&&!e){if(f=$.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&s(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!p||!p.test(a))){if(q=n=t,r=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){k=pb(a),(n=b.getAttribute("id"))?q=n.replace(ab,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=k.length;while(j--)k[j]=q+qb(k[j]);r=_.test(a)&&nb(b.parentNode)||b,v=k.join(",")}if(v)try{return H.apply(d,r.querySelectorAll(v)),d}catch(w){}finally{n||b.removeAttribute("id")}}}return yb(a.replace(Q,"$1"),b,d,e)}function fb(){var a=[];function b(c,d){return a.push(c+" ")>e.cacheLength&&delete b[a.shift()],b[c+" "]=d}return b}function gb(a){return a[t]=!0,a}function hb(a){var b=m.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ib(a,b){var c=a.split("|"),d=a.length;while(d--)e.attrHandle[c[d]]=b}function jb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function mb(a){return gb(function(b){return b=+b,gb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function nb(a){return a&&typeof a.getElementsByTagName!==B&&a}c=eb.support={},g=eb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},l=eb.setDocument=function(a){var b,d=a?a.ownerDocument||a:u,f=d.defaultView;return d!==m&&9===d.nodeType&&d.documentElement?(m=d,n=d.documentElement,o=!g(d),f&&f!==f.top&&(f.addEventListener?f.addEventListener("unload",function(){l()},!1):f.attachEvent&&f.attachEvent("onunload",function(){l()})),c.attributes=hb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=hb(function(a){return a.appendChild(d.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(d.getElementsByClassName)&&hb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=hb(function(a){return n.appendChild(a).id=t,!d.getElementsByName||!d.getElementsByName(t).length}),c.getById?(e.find.ID=function(a,b){if(typeof b.getElementById!==B&&o){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},e.filter.ID=function(a){var b=a.replace(bb,cb);return function(a){return a.getAttribute("id")===b}}):(delete e.find.ID,e.filter.ID=function(a){var b=a.replace(bb,cb);return function(a){var c=typeof a.getAttributeNode!==B&&a.getAttributeNode("id");return c&&c.value===b}}),e.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==B?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},e.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==B&&o?b.getElementsByClassName(a):void 0},q=[],p=[],(c.qsa=Z.test(d.querySelectorAll))&&(hb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&p.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||p.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll(":checked").length||p.push(":checked")}),hb(function(a){var b=d.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&p.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||p.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),p.push(",.*:")})),(c.matchesSelector=Z.test(r=n.webkitMatchesSelector||n.mozMatchesSelector||n.oMatchesSelector||n.msMatchesSelector))&&hb(function(a){c.disconnectedMatch=r.call(a,"div"),r.call(a,"[s!='']:x"),q.push("!=",P)}),p=p.length&&new RegExp(p.join("|")),q=q.length&&new RegExp(q.join("|")),b=Z.test(n.compareDocumentPosition),s=b||Z.test(n.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},A=b?function(a,b){if(a===b)return k=!0,0;var e=!a.compareDocumentPosition-!b.compareDocumentPosition;return e?e:(e=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&e||!c.sortDetached&&b.compareDocumentPosition(a)===e?a===d||a.ownerDocument===u&&s(u,a)?-1:b===d||b.ownerDocument===u&&s(u,b)?1:j?J.call(j,a)-J.call(j,b):0:4&e?-1:1)}:function(a,b){if(a===b)return k=!0,0;var c,e=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===d?-1:b===d?1:f?-1:g?1:j?J.call(j,a)-J.call(j,b):0;if(f===g)return jb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[e]===i[e])e++;return e?jb(h[e],i[e]):h[e]===u?-1:i[e]===u?1:0},d):m},eb.matches=function(a,b){return eb(a,null,null,b)},eb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==m&&l(a),b=b.replace(T,"='$1']"),!(!c.matchesSelector||!o||q&&q.test(b)||p&&p.test(b)))try{var d=r.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return eb(b,m,null,[a]).length>0},eb.contains=function(a,b){return(a.ownerDocument||a)!==m&&l(a),s(a,b)},eb.attr=function(a,b){(a.ownerDocument||a)!==m&&l(a);var d=e.attrHandle[b.toLowerCase()],f=d&&D.call(e.attrHandle,b.toLowerCase())?d(a,b,!o):void 0;return void 0!==f?f:c.attributes||!o?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},eb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},eb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(k=!c.detectDuplicates,j=!c.sortStable&&a.slice(0),a.sort(A),k){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return j=null,a},f=eb.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(1===e||9===e||11===e){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=f(a)}else if(3===e||4===e)return a.nodeValue}else while(b=a[d++])c+=f(b);return c},e=eb.selectors={cacheLength:50,createPseudo:gb,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(bb,cb),a[3]=(a[4]||a[5]||"").replace(bb,cb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||eb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&eb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return W.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&U.test(c)&&(b=pb(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(bb,cb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=x[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&x(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==B&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=eb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[t]||(q[t]={}),j=k[a]||[],n=j[0]===v&&j[1],m=j[0]===v&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[v,n,m];break}}else if(s&&(j=(b[t]||(b[t]={}))[a])&&j[0]===v)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[t]||(l[t]={}))[a]=[v,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,d=e.pseudos[a]||e.setFilters[a.toLowerCase()]||eb.error("unsupported pseudo: "+a);return d[t]?d(b):d.length>1?(c=[a,a,"",b],e.setFilters.hasOwnProperty(a.toLowerCase())?gb(function(a,c){var e,f=d(a,b),g=f.length;while(g--)e=J.call(a,f[g]),a[e]=!(c[e]=f[g])}):function(a){return d(a,0,c)}):d}},pseudos:{not:gb(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[t]?gb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:gb(function(a){return function(b){return eb(a,b).length>0}}),contains:gb(function(a){return function(b){return(b.textContent||b.innerText||f(b)).indexOf(a)>-1}}),lang:gb(function(a){return V.test(a||"")||eb.error("unsupported lang: "+a),a=a.replace(bb,cb).toLowerCase(),function(b){var c;do if(c=o?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===n},focus:function(a){return a===m.activeElement&&(!m.hasFocus||m.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!e.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:mb(function(){return[0]}),last:mb(function(a,b){return[b-1]}),eq:mb(function(a,b,c){return[0>c?c+b:c]}),even:mb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:mb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:mb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:mb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},e.pseudos.nth=e.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})e.pseudos[b]=kb(b);for(b in{submit:!0,reset:!0})e.pseudos[b]=lb(b);function ob(){}ob.prototype=e.filters=e.pseudos,e.setFilters=new ob;function pb(a,b){var c,d,f,g,h,i,j,k=y[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=e.preFilter;while(h){(!c||(d=R.exec(h)))&&(d&&(h=h.slice(d[0].length)||h),i.push(f=[])),c=!1,(d=S.exec(h))&&(c=d.shift(),f.push({value:c,type:d[0].replace(Q," ")}),h=h.slice(c.length));for(g in e.filter)!(d=W[g].exec(h))||j[g]&&!(d=j[g](d))||(c=d.shift(),f.push({value:c,type:g,matches:d}),h=h.slice(c.length));if(!c)break}return b?h.length:h?eb.error(a):y(a,i).slice(0)}function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var e=b.dir,f=c&&"parentNode"===e,g=w++;return b.first?function(b,c,d){while(b=b[e])if(1===b.nodeType||f)return a(b,c,d)}:function(b,c,h){var i,j,k,l=v+" "+g;if(h){while(b=b[e])if((1===b.nodeType||f)&&a(b,c,h))return!0}else while(b=b[e])if(1===b.nodeType||f)if(k=b[t]||(b[t]={}),(j=k[e])&&j[0]===l){if((i=j[1])===!0||i===d)return i===!0}else if(j=k[e]=[l],j[1]=a(b,c,h)||d,j[1]===!0)return!0}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function ub(a,b,c,d,e,f){return d&&!d[t]&&(d=ub(d)),e&&!e[t]&&(e=ub(e,f)),gb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||xb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:tb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=tb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=tb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function vb(a){for(var b,c,d,f=a.length,g=e.relative[a[0].type],h=g||e.relative[" "],j=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return J.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==i)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=e.relative[a[j].type])m=[rb(sb(m),c)];else{if(c=e.filter[a[j].type].apply(null,a[j].matches),c[t]){for(d=++j;f>d;d++)if(e.relative[a[d].type])break;return ub(j>1&&sb(m),j>1&&qb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(Q,"$1"),c,d>j&&vb(a.slice(j,d)),f>d&&vb(a=a.slice(d)),f>d&&qb(a))}m.push(c)}return sb(m)}function wb(a,b){var c=0,f=b.length>0,g=a.length>0,h=function(h,j,k,l,n){var o,p,q,r=0,s="0",t=h&&[],u=[],w=i,x=h||g&&e.find.TAG("*",n),y=v+=null==w?1:Math.random()||.1,z=x.length;for(n&&(i=j!==m&&j,d=c);s!==z&&null!=(o=x[s]);s++){if(g&&o){p=0;while(q=a[p++])if(q(o,j,k)){l.push(o);break}n&&(v=y,d=++c)}f&&((o=!q&&o)&&r--,h&&t.push(o))}if(r+=s,f&&s!==r){p=0;while(q=b[p++])q(t,u,j,k);if(h){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(l));u=tb(u)}H.apply(l,u),n&&!h&&u.length>0&&r+b.length>1&&eb.uniqueSort(l)}return n&&(v=y,i=w),t};return f?gb(h):h}h=eb.compile=function(a,b){var c,d=[],e=[],f=z[a+" "];if(!f){b||(b=pb(a)),c=b.length;while(c--)f=vb(b[c]),f[t]?d.push(f):e.push(f);f=z(a,wb(e,d))}return f};function xb(a,b,c){for(var d=0,e=b.length;e>d;d++)eb(a,b[d],c);return c}function yb(a,b,d,f){var g,i,j,k,l,m=pb(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&o&&e.relative[i[1].type]){if(b=(e.find.ID(j.matches[0].replace(bb,cb),b)||[])[0],!b)return d;a=a.slice(i.shift().value.length)}g=W.needsContext.test(a)?0:i.length;while(g--){if(j=i[g],e.relative[k=j.type])break;if((l=e.find[k])&&(f=l(j.matches[0].replace(bb,cb),_.test(i[0].type)&&nb(b.parentNode)||b))){if(i.splice(g,1),a=f.length&&qb(i),!a)return H.apply(d,f),d;break}}}return h(a,m)(f,b,!o,d,_.test(a)&&nb(b.parentNode)||b),d}return c.sortStable=t.split("").sort(A).join("")===t,c.detectDuplicates=!!k,l(),c.sortDetached=hb(function(a){return 1&a.compareDocumentPosition(m.createElement("div"))}),hb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ib("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&hb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ib("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),hb(function(a){return null==a.getAttribute("disabled")})||ib(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),eb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){var c="string"==typeof a?m(a,b):m.makeArray(a&&a.nodeType?[a]:a),d=m.merge(this.get(),c);return this.pushStack(m.unique(d))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,d=c.call(arguments),e=d.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,d){return function(e){b[a]=this,d[a]=arguments.length>1?c.call(arguments):e,d===i?g.notifyWith(b,d):--f||g.resolveWith(b,d)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)d[b]&&m.isFunction(d[b].promise)?d[b].promise().done(h(b,k,d)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,d),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.trigger&&m(y).trigger("ready").off("ready"))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c=y.getElementsByTagName("body")[0];c&&(a=y.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=y.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(k.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,c,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof c)return k||(k=i?a[h]=b.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof c||"function"==typeof c)&&(e?j[k]=m.extend(j[k],c):j[k].data=m.extend(j[k].data,c)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(c)]=d),"string"==typeof c?(f=g[c],null==f&&(f=g[m.camelCase(c)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d]));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createDocumentFragment(),b=y.createElement("div"),c=y.createElement("input");if(c.type="checkbox",b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,c.checked=!0,k.noCloneChecked=c.cloneNode(!0).checked,a.appendChild(c),k.appendChecked=c.checked,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,j,k,l,n,o=[d||y],p=i.call(b,"type")?b.type:b,q=i.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(j=k.delegateType||p,$.test(j+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?j:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,d,e,f,g,h=[],i=c.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,d=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),this[m.expando]=!0,void 0):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ab,this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:(m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))}),void 0)},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:(m.event.remove(this,"._submit"),void 0)}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):(m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))}),void 0)},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,c){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((c||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,b.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=d.apply([],a);var c,e,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)e=i,j!==o&&(e=m.clone(e,!0,!0),f&&m.merge(g,ub(e,"script"))),b.call(this[j],e,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)e=g[j],ob.test(e.type||"")&&!m._data(e,"globalEval")&&m.contains(h,e)&&(e.src?m._evalUrl&&m._evalUrl(e.src):m.globalEval((e.text||e.textContent||e.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,f=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),e.apply(f,c.get());return this.pushStack(f)}});var Cb,Db={};function Eb(b,c){var d=m(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:m.css(d[0],"display");return d.detach(),e}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a,b,c=y.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",k.opacity=/^0.5/.test(a.style.opacity),k.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,k.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=y.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=y.createElement("div"),e=y.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==K&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?(delete this.get,void 0):(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=y.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",k.opacity=/^0.5/.test(b.style.opacity),k.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,m.extend(k,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=y.createElement("div"),f=y.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=y.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&l(),d},boxSizingReliable:function(){return null==e&&l(),e},pixelPosition:function(){return null==f&&l(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=y.getElementsByTagName("body")[0],!b)return;c=y.createElement("div"),d=y.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(y.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function l(){var b,c,h=y.getElementsByTagName("body")[0];h&&(b=y.createElement("div"),c=y.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",m.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:0,fontWeight:400},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):f[g]||(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing()&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Ob.test(m.css(a,"display"))?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing()&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0]; return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l=Fb(a.nodeName),"none"===j&&(j=l),"inline"===j&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==l?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}if(!m.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){a()&&m.timers.push(a)&&m.fx.start()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=y.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=y.createElement("select"),d=c.appendChild(y.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",k.getSetAttribute="t"!==e.className,k.style=/top/.test(a.getAttribute("style")),k.hrefNormalized="/a"===a.getAttribute("href"),k.checkOn=!!b.value,k.optSelected=d.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!d.disabled,b=y.createElement("input"),b.setAttribute("value",""),k.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),k.radioValue="t"===b.value,a=b=c=d=e=null}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:a.text}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=m.inArray(m(d).val(),f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):(m.removeAttr(a,b),void 0))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?(a.defaultValue=b,void 0):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):m.isFunction(a)?this.each(function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return m.isFunction(a)?this.each(function(b){m(this).wrapInner(a.call(this,b))}):this.each(function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e,void 0)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m },a.jQuery=a.$=m,m}); //# sourceMappingURL=jquery.min.map
ajax/libs/6to5/3.0.1/browser-polyfill.js
davidbau/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){(function(global){"use strict";if(global._6to5Polyfill){throw new Error("only one instance of 6to5/polyfill is allowed")}global._6to5Polyfill=true;require("core-js/shim");require("regenerator-6to5/runtime")}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"core-js/shim":2,"regenerator-6to5/runtime":3}],2:[function(require,module,exports){!function(global,framework,undefined){"use strict";var OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_STRING_TAG=TO_STRING+"Tag",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",ITERATOR="iterator",FF_ITERATOR="@@"+ITERATOR,PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,setTimeout=global.setTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,process=global[PROCESS],nextTick=process&&process.nextTick,document=global.document,html=document&&document.documentElement,navigator=global.navigator,define=global.define,ArrayProto=Array[PROTOTYPE],ObjectProto=Object[PROTOTYPE],FunctionProto=Function[PROTOTYPE],Infinity=1/0,DOT=".";function isObject(it){return it!=null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var buildIn={Undefined:1,Null:1,Array:1,String:1,Arguments:1,Function:1,Error:1,Boolean:1,Number:1,Date:1,RegExp:1},toString=ObjectProto[TO_STRING];function setToStringTag(it,tag,stat){if(it&&!has(it=stat?it:it[PROTOTYPE],SYMBOL_TAG))hidden(it,SYMBOL_TAG,tag)}function cof(it){return it==undefined?it===undefined?"Undefined":"Null":toString.call(it).slice(8,-1)}function classof(it){var klass=cof(it),tag;return klass==OBJECT&&(tag=it[SYMBOL_TAG])?has(buildIn,tag)?"~"+tag:tag:klass}var call=FunctionProto.call,apply=FunctionProto.apply,REFERENCE_GET;function part(){var fn=assertFunction(this),length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,i=0,j=0,_args;if(!holder&&!_length)return invoke(fn,args,that);_args=args.slice();if(holder)for(;length>i;i++)if(_args[i]===_)_args[i]=arguments[j++];while(_length>j)_args.push(arguments[j++]);return invoke(fn,_args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){case 0:return un?fn():fn.call(that);case 1:return un?fn(args[0]):fn.call(that,args[0]);case 2:return un?fn(args[0],args[1]):fn.call(that,args[0],args[1]);case 3:return un?fn(args[0],args[1],args[2]):fn.call(that,args[0],args[1],args[2]);case 4:return un?fn(args[0],args[1],args[2],args[3]):fn.call(that,args[0],args[1],args[2],args[3]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}function construct(target,argumentsList){var instance=create((arguments.length<3?target:assertFunction(arguments[2]))[PROTOTYPE]),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,setPrototypeOf=Object.setPrototypeOf,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,getOwnDescriptor=Object.getOwnPropertyDescriptor,getKeys=Object.keys,getNames=Object.getOwnPropertyNames,getSymbols=Object.getOwnPropertySymbols,has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object,Dict;function toObject(it){return ES5Object(assertDefined(it))}function returnIt(it){return it}function returnThis(){return this}function get(object,key){if(has(object,key))return object[key]}function ownKeys(it){assertObject(it);return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(object,el){var O=toObject(object),keys=getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn){var O=Object(assertDefined(this)),that=arguments[1],self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el){var O=toObject(this),length=toLength(O.length),index=toIndex(arguments[1],length);if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},DOT,ObjectProto)}catch(e){}}(),sid=0,hidden=createDefiner(1),set=Symbol?simpleSet:hidden,safeSymbol=Symbol||uid;function assignHidden(target,src){for(var key in src)hidden(target,key,src[key]);return target}var SYMBOL_UNSCOPABLES=getWellKnownSymbol("unscopables"),ArrayUnscopables=ArrayProto[SYMBOL_UNSCOPABLES]||{},SYMBOL_SPECIES=getWellKnownSymbol("species");function setSpecies(C){if(framework||!isNative(C))defineProperty(C,SYMBOL_SPECIES,{configurable:true,get:returnThis})}var SYMBOL_ITERATOR=getWellKnownSymbol(ITERATOR),SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG),SUPPORT_FF_ITER=FF_ITERATOR in ArrayProto,ITER=safeSymbol("iter"),KEY=1,VALUE=2,Iterators={},IteratorPrototype={},NATIVE_ITERATORS=SYMBOL_ITERATOR in ArrayProto,BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);SUPPORT_FF_ITER&&hidden(O,FF_ITERATOR,value)}function createIterator(Constructor,NAME,next,proto){Constructor[PROTOTYPE]=create(proto||IteratorPrototype,{next:descriptor(1,next)});setToStringTag(Constructor,NAME+" Iterator")}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor[PROTOTYPE],iter=get(proto,SYMBOL_ITERATOR)||get(proto,FF_ITERATOR)||DEFAULT&&get(proto,DEFAULT)||value;if(framework){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis;return iter}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT,IS_SET){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);var entries=createIter(KEY+VALUE),values=createIter(VALUE);if(DEFAULT==VALUE)values=defineIterator(Base,NAME,values,"values");else entries=defineIterator(Base,NAME,entries,"entries");if(DEFAULT){$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:entries,keys:IS_SET?values:createIter(KEY),values:values})}}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it),Symbol=global[SYMBOL],hasExt=(Symbol&&Symbol[ITERATOR]||FF_ITERATOR)in O;return hasExt||SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){var Symbol=global[SYMBOL],ext=it[Symbol&&Symbol[ITERATOR]||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[classof(it)];return assertObject(getIter.call(it))}function stepCall(fn,value,entries){return entries?invoke(fn,value):fn(value)}function forOf(iterable,entries,fn,that){var iterator=getIterator(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done)if(stepCall(f,step.value,entries)===false)return}var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,exportGlobal,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(exports[key]!=out)hidden(exports,key,exp);if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}}}if(typeof module!="undefined"&&module.exports)module.exports=core;else if(isFunction(define)&&define.amd)define(function(){return core});else exportGlobal=true;if(exportGlobal||framework){core.noConflict=function(){global.core=old;return core};global.core=core}$define(GLOBAL+FORCED,{global:global});!function(TAG,SymbolRegistry,AllSymbols,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description);AllSymbols[tag]=true;DESC&&setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return set(create(Symbol[PROTOTYPE]),TAG,tag)};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR,keyFor:part.call(keyOf,SymbolRegistry),species:SYMBOL_SPECIES,toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),unscopables:SYMBOL_UNSCOPABLES,pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,split,toPrimitive"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(STATIC+FORCED*!isNative(Symbol),OBJECT,{getOwnPropertyNames:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])||result.push(key);return result},getOwnPropertySymbols:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])&&result.push(key);return result}})}(safeSymbol("tag"),{},{},true);!function(RegExpProto,isFinite,tmp,NAME){var RangeError=global.RangeError,isInteger=Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it},sign=Math.sign||function sign(x){return(x=+x)==0||x!=x?x:x<0?-1:1},E=Math.E,pow=Math.pow,abs=Math.abs,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,fcc=String.fromCharCode,at=createPointAt(true);var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=setPrototypeOf=setPrototypeOf||function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic);function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}function expm1(x){return(x=+x)==0?x:x>-1e-6&&x<1e-6?x+x*x/2:exp(x)-1}$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt});$define(STATIC,MATH,{acosh:function(x){return(x=+x)<1?NaN:isFinite(x)?log(x/E+sqrt(x+1)*sqrt(x-1)/E)+1:x},asinh:asinh,atanh:function(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function(x){return sign(x=+x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x=+x)+exp(-x))/2},expm1:expm1,fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,len1=arguments.length,len2=len1,args=Array(len1),larg=-Infinity,arg;while(len1--){arg=args[len1]=+arguments[len1];if(arg==Infinity||arg==-Infinity)return Infinity;if(arg>larg)larg=arg}larg=arg||1;while(len2--)sum+=pow(args[len2]/larg,2);return larg*sqrt(sum)},imul:function(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function(x){return(x=+x)>-1e-8&&x<1e-8?x-x*x/2:log(1+x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return abs(x=+x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)},tanh:function(x){var a=expm1(x=+x),b=expm1(-x);return a==Infinity?1:b==Infinity?-1:(a-b)/(exp(x)+exp(-x))},trunc:trunc});setToStringTag(Math,MATH,true);function assertNotRegExp(it){if(cof(it)==REGEXP)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(x){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fcc(code):fcc(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=toObject(callSite.raw),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString},includes:function(searchString){assertNotRegExp(searchString);return!!~String(assertDefined(this)).indexOf(searchString,arguments[1])},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),index=toLength(min(arguments[1],that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}});defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)});$define(STATIC,ARRAY,{from:function(arrayLike){var O=Object(assertDefined(arrayLike)),result=new(generic(this,Array)),mapfn=arguments[1],that=arguments[2],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,that,2):undefined,index=0,length;if(isIterable(O))for(var iter=getIterator(O),step;!(step=iter.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}else for(length=toLength(O.length);length>index;index++){result[index]=mapping?f(O[index],index):O[index]}result.length=index;return result},of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});$define(PROTO,ARRAY,{copyWithin:function(target,start){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],fin=end===undefined?len:toIndex(end,len),count=min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O},fill:function(value){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:toObject(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length)return iter.o=undefined,iterResult(1);if(kind==KEY)return iterResult(0,index);if(kind==VALUE)return iterResult(0,O[index]);return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];setToStringTag(global.JSON,"JSON",true);function wrapObjectMethod(key,MODE){var fn=Object[key],exp=core[OBJECT][key],f=0,o={};if(!exp||isNative(exp)){o[key]=MODE==1?function(it){return isObject(it)?fn(it):it}:MODE==2?function(it){return isObject(it)?fn(it):true}:MODE==3?function(it){return isObject(it)?fn(it):false}:MODE==4?function(it,key){return fn(toObject(it),key)}:function(it){return fn(toObject(it))};try{fn(DOT)}catch(e){f=1}$define(STATIC+FORCED*f,OBJECT,o)}}wrapObjectMethod("freeze",1);wrapObjectMethod("seal",1);wrapObjectMethod("preventExtensions",1);wrapObjectMethod("isFrozen",2);wrapObjectMethod("isSealed",2);wrapObjectMethod("isExtensible",3);wrapObjectMethod("getOwnPropertyDescriptor",4);wrapObjectMethod("getPrototypeOf");wrapObjectMethod("keys");wrapObjectMethod("getOwnPropertyNames");if(framework){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"});NAME in FunctionProto||defineProperty(FunctionProto,NAME,{configurable:true,get:function(){var match=String(this).match(/^\s*function ([^ (]*)/),name=match?match[1]:"";has(this,NAME)||defineProperty(this,NAME,descriptor(5,name));return name},set:function(value){has(this,NAME)||defineProperty(this,NAME,descriptor(0,value))}});if(DESC&&!function(){try{return RegExp(/a/g,"i")=="/a/i"}catch(e){}}()){var _RegExp=RegExp;RegExp=function RegExp(pattern,flags){return new _RegExp(cof(pattern)==REGEXP&&flags!==undefined?pattern.source:pattern,flags)};forEach.call(getNames(_RegExp),function(key){key in RegExp||defineProperty(RegExp,key,{configurable:true,get:function(){return _RegExp[key]},set:function(it){_RegExp[key]=it}})});RegExpProto[CONSTRUCTOR]=RegExp;RegExp[PROTOTYPE]=RegExpProto;hidden(global,REGEXP,RegExp)}if(/./g.flags!="g")defineProperty(RegExpProto,"flags",{configurable:true,get:createReplacer(/^.*\/(\w*)$/,"$1")});forEach.call(array("find,findIndex,fill,copyWithin,entries,keys,values"),function(it){ArrayUnscopables[it]=true});SYMBOL_UNSCOPABLES in ArrayProto||hidden(ArrayProto,SYMBOL_UNSCOPABLES,ArrayUnscopables)}setSpecies(RegExp);setSpecies(Array)}(RegExp[PROTOTYPE],isFinite,{},"name");isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(part.call(run,id),0)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(function(){}))==test||function(asap,DEF){function isThenable(o){var then;if(isObject(o))then=o.then;return isFunction(then)?then:false}function notify(def){var chain=def.chain;chain.length&&asap(function(){var msg=def.msg,ok=def.state==1,i=0;while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){ret=cb===true?msg:cb(msg);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(msg)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function resolve(msg){var def=this,then,wrapper;if(def.done)return;def.done=true;def=def.def||def;try{if(then=isThenable(msg)){wrapper={def:def,done:false};then.call(msg,ctx(resolve,wrapper,1),ctx(reject,wrapper,1))}else{def.msg=msg;def.state=1;notify(def)}}catch(err){reject.call(wrapper||{def:def,done:false},err)}}function reject(msg){var def=this;if(def.done)return;def.done=true;def=def.def||def;def.msg=msg;def.state=2;notify(def)}function getConstructor(C){var S=assertObject(C)[SYMBOL_SPECIES];return S!=undefined?S:C}Promise=function(executor){assertFunction(executor);assertInstance(this,Promise,PROMISE);var def={chain:[],state:0,done:false,msg:undefined};hidden(this,DEF,def);try{executor(ctx(resolve,def,1),ctx(reject,def,1))}catch(err){reject.call(def,err)}};assignHidden(Promise[PROTOTYPE],{then:function(onFulfilled,onRejected){var S=assertObject(assertObject(this)[CONSTRUCTOR])[SYMBOL_SPECIES];var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new(S!=undefined?S:Promise)(function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),def=this[DEF];def.chain.push(react);def.state&&notify(def);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=getConstructor(this),values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=getConstructor(this);return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new(getConstructor(this))(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&DEF in x&&getPrototypeOf(x)===this[PROTOTYPE]?x:new(getConstructor(this))(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("def"));setToStringTag(Promise,PROMISE);setSpecies(Promise);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var UID=safeSymbol("uid"),DATA=safeSymbol("data"),WEAK=safeSymbol("weak"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),SIZE=DESC?safeSymbol("size"):"size",uid=0;function getCollection(C,NAME,methods,commonMethods,isMap,isWeak){var ADDER=isMap?"set":"add",proto=C&&C[PROTOTYPE],O={};function initFromIterable(that,iterable){if(iterable!=undefined)forOf(iterable,isMap,that[ADDER],that);return that}function fixSVZ(key,chain){var method=proto[key];framework&&hidden(proto,key,function(a,b){var result=method.call(this,a===0?0:a,b);return chain?this:result})}if(!isNative(C)||!(isWeak||!BUGGY_ITERATORS&&has(proto,"entries"))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,UID,uid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,DATA,create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);initFromIterable(that,iterable)};assignHidden(assignHidden(C[PROTOTYPE],methods),commonMethods);isWeak||defineProperty(C[PROTOTYPE],"size",{get:function(){return assertDefined(this[SIZE])}})}else{var Native=C,inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(!NATIVE_ITERATORS||!C.length){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);setSpecies(C);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);isWeak||defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!O||!(iter.l=entry=entry?entry.n:O[FIRST]))return iter.o=undefined,iterResult(1);if(kind==KEY)return iterResult(0,entry.k);if(kind==VALUE)return iterResult(0,entry.v);return iterResult(0,[entry.k,entry.v])},isMap?KEY+VALUE:VALUE,!isMap);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(!has(it,UID)){if(create)hidden(it,UID,++uid);else return""}return"O"+it[UID]}function def(that,key,value){var index=fastKey(key,true),data=that[DATA],last=that[LAST],entry;if(index in data)data[index].v=value;else{entry=data[index]={k:key,v:value,p:last};if(!that[FIRST])that[FIRST]=entry;if(last)last.n=entry;that[LAST]=entry;that[SIZE]++}return that}function del(that,index){var data=that[DATA],entry=data[index],next=entry.n,prev=entry.p;delete data[index];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}var collectionMethods={clear:function(){for(var index in this[DATA])del(this,index)},"delete":function(key){var index=fastKey(key),contains=index in this[DATA];if(contains)del(this,index);return contains},forEach:function(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return fastKey(key)in this[DATA]}};Map=getCollection(Map,MAP,{get:function(key){var entry=this[DATA][fastKey(key)];return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function setWeak(that,key,value){has(assertObject(key),WEAK)||hidden(key,WEAK,{});key[WEAK][that[UID]]=value;return that}function hasWeak(key){return isObject(key)&&has(key,WEAK)&&has(key[WEAK],this[UID])}var weakMethods={"delete":function(key){return hasWeak.call(this,key)&&delete key[WEAK][this[UID]]},has:hasWeak};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)&&has(key,WEAK))return key[WEAK][this[UID]]},set:function(key,value){return setWeak(this,key,value)}},weakMethods,true,true);WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){return setWeak(this,value,true)}},weakMethods,false,true)}();!function(){function Enumerate(iterated){var keys=[],key;for(key in iterated)keys.push(key);set(this,ITER,{o:iterated,a:keys,i:0})}createIterator(Enumerate,OBJECT,function(){var iter=this[ITER],keys=iter.a,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!((key=keys[iter.i++])in iter.o));return iterResult(0,key)});function wrap(fn){return function(it){assertObject(it);try{return fn.apply(undefined,arguments),true}catch(e){return false}}}function reflectGet(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc)return desc.get?desc.get.call(receiver):desc.value;return isObject(proto=getPrototypeOf(target))?reflectGet(proto,propertyKey,receiver):undefined}function reflectSet(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],desc=getOwnDescriptor(assertObject(target),propertyKey),proto; if(desc){if(desc.writable===false)return false;if(desc.set)return desc.set.call(receiver,V),true}if(isObject(proto=getPrototypeOf(target)))return reflectSet(proto,propertyKey,V,receiver);desc=getOwnDescriptor(receiver,propertyKey)||descriptor(0);desc.value=V;return defineProperty(receiver,propertyKey,desc),true}var isExtensible=Object.isExtensible||returnIt;var reflect={apply:ctx(call,apply,3),construct:construct,defineProperty:wrap(defineProperty),deleteProperty:function(target,propertyKey){var desc=getOwnDescriptor(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function(target){return new Enumerate(assertObject(target))},get:reflectGet,getOwnPropertyDescriptor:function(target,propertyKey){return getOwnDescriptor(assertObject(target),propertyKey)},getPrototypeOf:function(target){return getPrototypeOf(assertObject(target))},has:function(target,propertyKey){return propertyKey in target},isExtensible:function(target){return!!isExtensible(assertObject(target))},ownKeys:ownKeys,preventExtensions:wrap(Object.preventExtensions||returnIt),set:reflectSet};if(setPrototypeOf)reflect.setPrototypeOf=function(target,proto){return setPrototypeOf(assertObject(target),proto),true};$define(GLOBAL,{Reflect:{}});$define(STATIC,"Reflect",reflect)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=toObject(object),keys=getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$define(STATIC,OBJECT,{values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(NodeList){if(framework&&NodeList&&!(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){hidden(NodeList[PROTOTYPE],SYMBOL_ITERATOR,Iterators[ARRAY])}Iterators.NodeList=Iterators[ARRAY]}(global.NodeList);!function(arrayStatics){function setArrayStatics(keys,length){forEach.call(array(keys),function(key){if(key in ArrayProto)arrayStatics[key]=ctx(call,ArrayProto[key],length)})}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$define(STATIC,ARRAY,arrayStatics)}({})}(typeof self!="undefined"&&self.Math===Math?self:Function("return this")(),true)},{}],3:[function(require,module,exports){(function(global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])}runtime.wrap=wrap;function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var record=tryCatch(this,null,arg);if(record.type==="throw"){reject(record.arg);return}var info=record.arg;if(info.done){resolve(info.value)}else{Promise.resolve(info.value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}method="next";arg=undefined;var info=record.arg;if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;if(method==="next"){context.dispatchException(record.arg)}else{arg=record.arg}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1,next=function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next};return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}(typeof global==="object"?global:typeof window==="object"?window:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}]},{},[1]);
src/jsx/ExerciseConfiguration.js
vkaravir/js-parsons-editor
import React from 'react'; const ExerciseConfiguration = (props) => { var _ = props._; var config = Object.assign({}, props.config); var codelines = config.codelines; delete config.codelines; var configStr = 'var options = ' + JSON.stringify(config, null, 2) + ';\n' + 'var codelines = "' + codelines.replace(/\n/g, '\\n').replace(/"/g, '\\\"') + '";\n\n' + 'var parson = new ParsonsWidget(options);\n' + 'parson.init(codelines);'; return ( <div className="jsparsons-exercise-config__container"> <div className="jsparsons-preview__header"> <a href="#" className="fa fa-close fa-2x jsparsons-preview__link" onClick={props.close}></a> <h3 className="jsparsons-preview__title">{_('CONFIGURATION_TITLE')}</h3> </div> <textarea className="jsparsons-exercise-config__code" defaultValue={configStr}></textarea> </div> ); }; export default ExerciseConfiguration;
components/com_jhotelreservation/assets/js/jquery.min.js
mssnaveensharma/mjejaneriver-jaqui
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery-1.10.2.min.map */ (function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t }({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Ct=/^(?:checkbox|radio)$/i,Nt=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(x.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(T)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(mn[3]||("http:"===mn[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,Fn.push(o)),s&&x.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=x.timers,a=x._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,x.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
NavigationReactMobile/sample/twitter/Twitter.js
grahammendick/navigation
import React from 'react'; import {NavigationMotion, Scene} from 'navigation-react-mobile'; import PhotoZoom from './PhotoZoom'; import Home from './Home'; import Tweet from './Tweet'; import Timeline from './Timeline'; import Photo from './Photo'; export default () => ( <NavigationMotion unmountedStyle={(state, data, crumbs) => { var {state: previousState, data: previousData} = crumbs[crumbs.length - 1]; var sharePhoto = state.key === 'photo' && !(previousState.key === 'tweet' && previousData.id === data.id); return !sharePhoto ? {translate: 100, scale: 1, opacity: 1} : {translate: 0, scale: 1, opacity: 0}; }} mountedStyle={{translate: 0, scale: 1, opacity: 1}} crumbStyle={(state, data, crumbs, nextState) => ( nextState.key !== 'photo' ? {translate: 5, scale: 0.9, opacity: 0} : {translate: 0, scale: 1, opacity: 0} )} sharedElementMotion={({sharedElements, ...props}) => { sharedElements = sharedElements.filter(share => share.oldElement.data.enable || share.mountedElement.data.enable); return <PhotoZoom {...props} sharedElements={sharedElements} />; }} renderMotion={({translate, scale, opacity}, scene, key) => ( <div key={key} className="scene" style={{ transform: `translate(${translate}%) scale(${scale}, ${scale})`, opacity }}> {scene} </div> )}> <Scene stateKey="home"><Home /></Scene> <Scene stateKey="tweet"><Tweet /></Scene> <Scene stateKey="timeline"><Timeline /></Scene> <Scene stateKey="photo"><Photo /></Scene> </NavigationMotion> );
ajax/libs/react-dom/16.0.0-alpha.11/umd/react-dom-server.development.js
sashberd/cdnjs
/** * react-dom-server.development.js v16.0.0-alpha.11 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) : typeof define === 'function' && define.amd ? define(['react'], factory) : (global.ReactDOMServer = factory(global.React)); }(this, (function (React) { 'use strict'; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ARIADOMPropertyConfig */ var ARIADOMPropertyConfig = { Properties: { // Global States and Properties 'aria-current': 0, // state 'aria-details': 0, 'aria-disabled': 0, // state 'aria-hidden': 0, // state 'aria-invalid': 0, // state 'aria-keyshortcuts': 0, 'aria-label': 0, 'aria-roledescription': 0, // Widget Attributes 'aria-autocomplete': 0, 'aria-checked': 0, 'aria-expanded': 0, 'aria-haspopup': 0, 'aria-level': 0, 'aria-modal': 0, 'aria-multiline': 0, 'aria-multiselectable': 0, 'aria-orientation': 0, 'aria-placeholder': 0, 'aria-pressed': 0, 'aria-readonly': 0, 'aria-required': 0, 'aria-selected': 0, 'aria-sort': 0, 'aria-valuemax': 0, 'aria-valuemin': 0, 'aria-valuenow': 0, 'aria-valuetext': 0, // Live Region Attributes 'aria-atomic': 0, 'aria-busy': 0, 'aria-live': 0, 'aria-relevant': 0, // Drag-and-Drop Attributes 'aria-dropeffect': 0, 'aria-grabbed': 0, // Relationship Attributes 'aria-activedescendant': 0, 'aria-colcount': 0, 'aria-colindex': 0, 'aria-colspan': 0, 'aria-controls': 0, 'aria-describedby': 0, 'aria-errormessage': 0, 'aria-flowto': 0, 'aria-labelledby': 0, 'aria-owns': 0, 'aria-posinset': 0, 'aria-rowcount': 0, 'aria-rowindex': 0, 'aria-rowspan': 0, 'aria-setsize': 0 }, DOMAttributeNames: {}, DOMPropertyNames: {} }; var ARIADOMPropertyConfig_1 = ARIADOMPropertyConfig; /** * 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. * * @providesModule reactProdInvariant * */ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * Use 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 validateFormat = function validateFormat(format) {}; { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); 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; } } var invariant_1 = invariant; /** * Injectable ordering of event plugins. */ var eventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!eventPluginOrder) { // Wait until an `eventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var pluginModule = namesToPlugins[pluginName]; var pluginIndex = eventPluginOrder.indexOf(pluginName); !(pluginIndex > -1) ? invariant_1(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : void 0; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !pluginModule.extractEvents ? invariant_1(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : void 0; EventPluginRegistry.plugins[pluginIndex] = pluginModule; var publishedEvents = pluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? invariant_1(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : void 0; } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? invariant_1(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : void 0; EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, pluginModule, eventName); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, pluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? invariant_1(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : void 0; EventPluginRegistry.registrationNameModules[registrationName] = pluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; { var lowerCasedName = registrationName.toLowerCase(); EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === 'onDoubleClick') { EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName; } } } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in true. * @type {Object} */ possibleRegistrationNames: {}, // Trust the developer to only use possibleRegistrationNames in true /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (injectedEventPluginOrder) { !!eventPluginOrder ? invariant_1(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : void 0; // Clone the ordering so it cannot be dynamically mutated. eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function (injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var pluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) { !!namesToPlugins[pluginName] ? invariant_1(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : void 0; namesToPlugins[pluginName] = pluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } } }; var EventPluginRegistry_1 = EventPluginRegistry; var caughtError = null; var invokeGuardedCallback = function (name, func, context, a, b, c, d, e, f) { var funcArgs = Array.prototype.slice.call(arguments, 3); try { func.apply(context, funcArgs); } catch (error) { return error; } return null; }; { /** * To help development we can get better devtools integration by simulating a * real browser event. */ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); var depth = 0; invokeGuardedCallback = function (name, func, context, a, b, c, d, e, f) { depth++; var thisDepth = depth; var funcArgs = Array.prototype.slice.call(arguments, 3); var boundFunc = function () { func.apply(context, funcArgs); }; var fakeEventError = null; var onFakeEventError = function (event) { // Don't capture nested errors if (depth === thisDepth) { fakeEventError = event.error; } }; var evtType = 'react-' + (name ? name : 'invokeguardedcallback') + '-' + depth; window.addEventListener('error', onFakeEventError); fakeNode.addEventListener(evtType, boundFunc, false); var evt = document.createEvent('Event'); evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); fakeNode.removeEventListener(evtType, boundFunc, false); window.removeEventListener('error', onFakeEventError); depth--; return fakeEventError; }; } } var rethrowCaughtError = function () { if (caughtError) { var error = caughtError; caughtError = null; throw error; } }; var ReactErrorUtils = { injection: { injectErrorUtils: function (injectedErrorUtils) { invariant_1(typeof injectedErrorUtils.invokeGuardedCallback === 'function', 'Injected invokeGuardedCallback() must be a function.'); invokeGuardedCallback = injectedErrorUtils.invokeGuardedCallback; } }, /** * Call a function while guarding against errors that happens within it. * Returns an error if it throws, otherwise null. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ invokeGuardedCallback: function (name, func, context, a, b, c, d, e, f) { return invokeGuardedCallback.apply(this, arguments); }, /** * Same as invokeGuardedCallback, but instead of returning an error, it stores * it in a global so it can be rethrown by `rethrowCaughtError` later. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ invokeGuardedCallbackAndCatchFirstError: function (name, func, context, a, b, c, d, e, f) { var error = ReactErrorUtils.invokeGuardedCallback.apply(this, arguments); if (error !== null && caughtError === null) { caughtError = error; } }, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function () { return rethrowCaughtError.apply(this, arguments); } }; var ReactErrorUtils_1 = ReactErrorUtils; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; var emptyFunction_1 = emptyFunction; /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction_1; { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } var warning_1 = warning; /** * Injected dependencies: */ /** * - `ComponentTree`: [required] Module that can convert between React instances * and actual node references. */ var ComponentTree; var injection = { injectComponentTree: function (Injected) { ComponentTree = Injected; { warning_1(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.'); } } }; function isEndish(topLevelType) { return topLevelType === 'topMouseUp' || topLevelType === 'topTouchEnd' || topLevelType === 'topTouchCancel'; } function isMoveish(topLevelType) { return topLevelType === 'topMouseMove' || topLevelType === 'topTouchMove'; } function isStartish(topLevelType) { return topLevelType === 'topMouseDown' || topLevelType === 'topTouchStart'; } var validateEventDispatches; { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; warning_1(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.'); }; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ function executeDispatch(event, simulated, listener, inst) { var type = event.type || 'unknown-event'; event.currentTarget = EventPluginUtils.getNodeFromInstance(inst); ReactErrorUtils_1.invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchInstances); } event._dispatchListeners = null; event._dispatchInstances = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchInstances)) { return dispatchInstances; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; !!Array.isArray(dispatchListener) ? invariant_1(false, 'executeDirectDispatch(...): Invalid `event`.') : void 0; event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; var res = dispatchListener ? dispatchListener(event) : null; event.currentTarget = null; event._dispatchListeners = null; event._dispatchInstances = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getFiberCurrentPropsFromNode: function (node) { return ComponentTree.getFiberCurrentPropsFromNode(node); }, getInstanceFromNode: function (node) { return ComponentTree.getInstanceFromNode(node); }, getNodeFromInstance: function (node) { return ComponentTree.getNodeFromInstance(node); }, injection: injection }; var EventPluginUtils_1 = EventPluginUtils; /** * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { !(next != null) ? invariant_1(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : void 0; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). if (Array.isArray(current)) { if (Array.isArray(next)) { current.push.apply(current, next); return current; } current.push(next); return current; } if (Array.isArray(next)) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } var accumulateInto_1 = accumulateInto; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule forEachAccumulated * */ /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). * @param {function} cb Callback invoked with each element or a collection. * @param {?} [scope] Scope used as `this` in a callback. */ function forEachAccumulated(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } } var forEachAccumulated_1 = forEachAccumulated; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @param {boolean} simulated If the event is simulated (changes exn behavior) * @private */ var executeDispatchesAndRelease = function (event, simulated) { if (event) { EventPluginUtils_1.executeDispatchesInOrder(event, simulated); if (!event.isPersistent()) { event.constructor.release(event); } } }; var executeDispatchesAndReleaseSimulated = function (e) { return executeDispatchesAndRelease(e, true); }; var executeDispatchesAndReleaseTopLevel = function (e) { return executeDispatchesAndRelease(e, false); }; function isInteractive(tag) { return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; } function shouldPreventMouseEvent(name, type, props) { switch (name) { case 'onClick': case 'onClickCapture': case 'onDoubleClick': case 'onDoubleClickCapture': case 'onMouseDown': case 'onMouseDownCapture': case 'onMouseMove': case 'onMouseMoveCapture': case 'onMouseUp': case 'onMouseUpCapture': return !!(props.disabled && isInteractive(type)); default: return false; } } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry_1.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry_1.injectEventPluginsByName }, /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (inst, registrationName) { var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not // live here; needs to be moved to a better place soon if (typeof inst.tag === 'number') { var stateNode = inst.stateNode; if (!stateNode) { // Work in progress (ex: onload events in incremental mode). return null; } var props = EventPluginUtils_1.getFiberCurrentPropsFromNode(stateNode); if (!props) { // Work in progress. return null; } listener = props[registrationName]; if (shouldPreventMouseEvent(registrationName, inst.type, props)) { return null; } } else { var currentElement = inst._currentElement; if (typeof currentElement === 'string' || typeof currentElement === 'number') { // Text node, let it bubble through. return null; } if (!inst._rootNodeID) { // If the instance is already unmounted, we have no listeners. return null; } var _props = currentElement.props; listener = _props[registrationName]; if (shouldPreventMouseEvent(registrationName, currentElement.type, _props)) { return null; } } !(!listener || typeof listener === 'function') ? invariant_1(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : void 0; return listener; }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events; var plugins = EventPluginRegistry_1.plugins; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); if (extractedEvents) { events = accumulateInto_1(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function (events) { if (events) { eventQueue = accumulateInto_1(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function (simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; if (simulated) { forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseSimulated); } else { forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseTopLevel); } !!eventQueue ? invariant_1(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : void 0; // This would be a good time to rethrow if any of the event handlers threw. ReactErrorUtils_1.rethrowCaughtError(); } }; var EventPluginHub_1 = EventPluginHub; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTypeOfWork * */ var ReactTypeOfWork = { IndeterminateComponent: 0, // Before we know whether it is functional or class FunctionalComponent: 1, ClassComponent: 2, HostRoot: 3, // Root of a host tree. Could be nested inside another node. HostPortal: 4, // A subtree. Could be an entry point to a different renderer. HostComponent: 5, HostText: 6, CoroutineComponent: 7, CoroutineHandlerPhase: 8, YieldComponent: 9, Fragment: 10 }; var HostComponent = ReactTypeOfWork.HostComponent; function getParent(inst) { if (inst._hostParent !== undefined) { return inst._hostParent; } if (typeof inst.tag === 'number') { do { inst = inst['return']; // TODO: If this is a HostRoot we might want to bail out. // That is depending on if we want nested subtrees (layers) to bubble // events to their parent. We could also go through parentNode on the // host node but that wouldn't work for React Native and doesn't let us // do the portal feature. } while (inst && inst.tag !== HostComponent); if (inst) { return inst; } } return null; } /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { var depthA = 0; for (var tempA = instA; tempA; tempA = getParent(tempA)) { depthA++; } var depthB = 0; for (var tempB = instB; tempB; tempB = getParent(tempB)) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = getParent(instA); depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = getParent(instB); depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (instA === instB || instA === instB.alternate) { return instA; } instA = getParent(instA); instB = getParent(instB); } return null; } /** * Return if A is an ancestor of B. */ function isAncestor(instA, instB) { while (instB) { if (instA === instB || instA === instB.alternate) { return true; } instB = getParent(instB); } return false; } /** * Return the parent instance of the passed-in instance. */ function getParentInstance(inst) { return getParent(inst); } /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ function traverseTwoPhase(inst, fn, arg) { var path = []; while (inst) { path.push(inst); inst = getParent(inst); } var i; for (i = path.length; i-- > 0;) { fn(path[i], 'captured', arg); } for (i = 0; i < path.length; i++) { fn(path[i], 'bubbled', arg); } } /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * Does not invoke the callback on the nearest common ancestor because nothing * "entered" or "left" that element. */ function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (from && from !== common) { pathFrom.push(from); from = getParent(from); } var pathTo = []; while (to && to !== common) { pathTo.push(to); to = getParent(to); } var i; for (i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], 'bubbled', argFrom); } for (i = pathTo.length; i-- > 0;) { fn(pathTo[i], 'captured', argTo); } } var ReactTreeTraversal = { isAncestor: isAncestor, getLowestCommonAncestor: getLowestCommonAncestor, getParentInstance: getParentInstance, traverseTwoPhase: traverseTwoPhase, traverseEnterLeave: traverseEnterLeave }; var getListener = EventPluginHub_1.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(inst, phase, event) { { warning_1(inst, 'Dispatching inst must not be null'); } var listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { ReactTreeTraversal.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? ReactTreeTraversal.getParentInstance(targetInst) : null; ReactTreeTraversal.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(inst, ignoredDirection, event) { if (inst && event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, from, to) { ReactTreeTraversal.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated_1(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing even a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; var EventPropagators_1 = EventPropagators; /** * 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. * */ var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; var ExecutionEnvironment_1 = ExecutionEnvironment; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; 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 no-new-wrappers 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 (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var index = 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 (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? invariant_1(false, 'Trying to release an instance into a pool of a different type.') : void 0; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances. * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { // Casting as any so that flow ignores the actual implementation and trusts // it to match the type we declared var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler }; var PooledClass_1 = PooledClass; var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment_1.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } var getTextContentAccessor_1 = getTextContentAccessor; /** * This helper class stores information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this._root = root; this._startText = this.getText(); this._fallbackText = null; } index(FallbackCompositionState.prototype, { destructor: function () { this._root = null; this._startText = null; this._fallbackText = null; }, /** * Get current text of input. * * @return {string} */ getText: function () { if ('value' in this._root) { return this._root.value; } return this._root[getTextContentAccessor_1()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function () { if (this._fallbackText) { return this._fallbackText; } var start; var startValue = this._startText; var startLength = startValue.length; var end; var endValue = this.getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; this._fallbackText = endValue.slice(start, sliceTail); return this._fallbackText; } }); PooledClass_1.addPoolingTo(FallbackCompositionState); var FallbackCompositionState_1 = FallbackCompositionState; var didWarnForAddedNewProperty = false; var isProxySupported = typeof Proxy === 'function'; var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances']; /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction_1.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {*} targetInst Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { { // these have a getter/setter for warnings delete this.nativeEvent; delete this.preventDefault; delete this.stopPropagation; } this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } { delete this[propName]; // this has a getter/setter for warnings } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction_1.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction_1.thatReturnsFalse; } this.isPropagationStopped = emptyFunction_1.thatReturnsFalse; return this; } index(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else if (typeof event.returnValue !== 'unknown') { event.returnValue = false; } this.isDefaultPrevented = emptyFunction_1.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else if (typeof event.cancelBubble !== 'unknown') { // The ChangeEventPlugin registers a "propertychange" event for // IE. This event does not support bubbling or cancelling, and // any references to cancelBubble throw "Member not found". A // typeof check of "unknown" circumvents this issue (and is also // IE specific). event.cancelBubble = true; } this.isPropagationStopped = emptyFunction_1.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = emptyFunction_1.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction_1.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { { Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); } } for (var i = 0; i < shouldBeReleasedProperties.length; i++) { this[shouldBeReleasedProperties[i]] = null; } { Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction_1)); Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction_1)); } } }); SyntheticEvent.Interface = EventInterface; { if (isProxySupported) { /*eslint-disable no-func-assign */ SyntheticEvent = new Proxy(SyntheticEvent, { construct: function (target, args) { return this.apply(target, Object.create(target.prototype), args); }, apply: function (constructor, that, args) { return new Proxy(constructor.apply(that, args), { set: function (target, prop, value) { if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) { warning_1(didWarnForAddedNewProperty || target.isPersistent(), "This synthetic event is reused for performance reasons. If you're " + "seeing this, you're adding a new property in the synthetic event object. " + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.'); didWarnForAddedNewProperty = true; } target[prop] = value; return true; } }); } }); /*eslint-enable no-func-assign */ } } /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var E = function () {}; E.prototype = Super.prototype; var prototype = new E(); index(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = index({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass_1.addPoolingTo(Class, PooledClass_1.fourArgumentPooler); }; PooledClass_1.addPoolingTo(SyntheticEvent, PooledClass_1.fourArgumentPooler); var SyntheticEvent_1 = SyntheticEvent; /** * Helper to nullify syntheticEvent instance properties when destructing * * @param {object} SyntheticEvent * @param {String} propName * @return {object} defineProperty object */ function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; warning_1(warningCondition, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result); } } /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent_1.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); var SyntheticCompositionEvent_1 = SyntheticCompositionEvent; /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent_1.augmentClass(SyntheticInputEvent, InputEventInterface); var SyntheticInputEvent_1 = SyntheticInputEvent; var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = ExecutionEnvironment_1.canUseDOM && 'CompositionEvent' in window; var documentMode = null; if (ExecutionEnvironment_1.canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ExecutionEnvironment_1.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto(); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = ExecutionEnvironment_1.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: 'onBeforeInput', captured: 'onBeforeInputCapture' }, dependencies: ['topCompositionEnd', 'topKeyPress', 'topTextInput', 'topPaste'] }, compositionEnd: { phasedRegistrationNames: { bubbled: 'onCompositionEnd', captured: 'onCompositionEndCapture' }, dependencies: ['topBlur', 'topCompositionEnd', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] }, compositionStart: { phasedRegistrationNames: { bubbled: 'onCompositionStart', captured: 'onCompositionStartCapture' }, dependencies: ['topBlur', 'topCompositionStart', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] }, compositionUpdate: { phasedRegistrationNames: { bubbled: 'onCompositionUpdate', captured: 'onCompositionUpdateCapture' }, dependencies: ['topBlur', 'topCompositionUpdate', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] } }; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case 'topCompositionStart': return eventTypes.compositionStart; case 'topCompositionEnd': return eventTypes.compositionEnd; case 'topCompositionUpdate': return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return topLevelType === 'topKeyDown' && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case 'topKeyUp': // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case 'topKeyDown': // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case 'topKeyPress': case 'topMouseDown': case 'topBlur': // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } // Track the current IME composition fallback object, if any. var currentComposition = null; /** * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState_1.getPooled(nativeEventTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent_1.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators_1.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case 'topCompositionEnd': return getDataFromCustomEvent(nativeEvent); case 'topKeyPress': /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case 'topTextInput': // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. // If composition event is available, we extract a string only at // compositionevent, otherwise extract it at fallback events. if (currentComposition) { if (topLevelType === 'topCompositionEnd' || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); FallbackCompositionState_1.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case 'topPaste': // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case 'topKeyPress': /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case 'topCompositionEnd': return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent_1.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators_1.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)]; } }; var BeforeInputEventPlugin_1 = BeforeInputEventPlugin; function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_PROPERTY: 0x1, HAS_BOOLEAN_VALUE: 0x4, HAS_NUMERIC_VALUE: 0x8, HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8, HAS_OVERLOADED_BOOLEAN_VALUE: 0x20, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMAttributeNamespaces: object mapping React attribute name to the DOM * attribute namespace URL. (Attribute names not specified use no namespace.) * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function (domPropertyConfig) { var Injection = DOMPropertyInjection; var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); } for (var propName in Properties) { !!DOMProperty.properties.hasOwnProperty(propName) ? invariant_1(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property \'%s\' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.', propName) : void 0; var lowerCased = propName.toLowerCase(); var propConfig = Properties[propName]; var propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) }; !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? invariant_1(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : void 0; { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; { DOMProperty.getPossibleStandardName[attributeName] = propName; } } if (DOMAttributeNamespaces.hasOwnProperty(propName)) { propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; } if (DOMPropertyNames.hasOwnProperty(propName)) { propertyInfo.propertyName = DOMPropertyNames[propName]; } if (DOMMutationMethods.hasOwnProperty(propName)) { propertyInfo.mutationMethod = DOMMutationMethods[propName]; } DOMProperty.properties[propName] = propertyInfo; } } }; /* eslint-disable max-len */ var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; /* eslint-enable max-len */ /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', ROOT_ATTRIBUTE_NAME: 'data-reactroot', ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR, ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040', /** * Map from property "standard name" to an object with info about how to set * the property in the DOM. Each object contains: * * attributeName: * Used when rendering markup or with `*Attribute()`. * attributeNamespace * propertyName: * Used on DOM node instances. (This includes properties that mutate due to * external factors.) * mutationMethod: * If non-null, used instead of the property or `setAttribute()` after * initial render. * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * hasBooleanValue: * Whether the property should be removed when set to a falsey value. * hasNumericValue: * Whether the property must be numeric or parse as a numeric and should be * removed when set to a falsey value. * hasPositiveNumericValue: * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * hasOverloadedBooleanValue: * Whether the property can be used as a flag as well as with a value. * Removed when strictly equal to false; present without a value when * strictly equal to true; present with a value otherwise. */ properties: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. Available only in true. * * autofocus is predefined, because adding it to the property whitelist * causes unintended side effects. * * @type {Object} */ getPossibleStandardName: { autofocus: 'autoFocus' }, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function (attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, injection: DOMPropertyInjection }; var DOMProperty_1 = DOMProperty; // Use to restore controlled state after a change event has fired. var fiberHostComponent = null; var ReactControlledComponentInjection = { injectFiberControlledHostComponent: function (hostComponentImpl) { // The fiber implementation doesn't use dynamic dispatch so we need to // inject the implementation. fiberHostComponent = hostComponentImpl; } }; var restoreTarget = null; var restoreQueue = null; function restoreStateOfTarget(target) { // We perform this translation at the end of the event loop so that we // always receive the correct fiber here var internalInstance = EventPluginUtils_1.getInstanceFromNode(target); if (!internalInstance) { // Unmounted return; } if (typeof internalInstance.tag === 'number') { invariant_1(fiberHostComponent && typeof fiberHostComponent.restoreControlledState === 'function', 'Fiber needs to be injected to handle a fiber target for controlled ' + 'events.'); var props = EventPluginUtils_1.getFiberCurrentPropsFromNode(internalInstance.stateNode); fiberHostComponent.restoreControlledState(internalInstance.stateNode, internalInstance.type, props); return; } invariant_1(typeof internalInstance.restoreControlledState === 'function', 'The internal instance must be a React host component.'); // If it is not a Fiber, we can just use dynamic dispatch. internalInstance.restoreControlledState(); } var ReactControlledComponent = { injection: ReactControlledComponentInjection, enqueueStateRestore: function (target) { if (restoreTarget) { if (restoreQueue) { restoreQueue.push(target); } else { restoreQueue = [target]; } } else { restoreTarget = target; } }, restoreStateIfNeeded: function () { if (!restoreTarget) { return; } var target = restoreTarget; var queuedTargets = restoreQueue; restoreTarget = null; restoreQueue = null; restoreStateOfTarget(target); if (queuedTargets) { for (var i = 0; i < queuedTargets.length; i++) { restoreStateOfTarget(queuedTargets[i]); } } } }; var ReactControlledComponent_1 = ReactControlledComponent; /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponentFlags */ var ReactDOMComponentFlags = { hasCachedChildNodes: 1 << 0 }; var ReactDOMComponentFlags_1 = ReactDOMComponentFlags; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule HTMLNodeType */ /** * HTML nodeType values that represent the type of the node */ var HTMLNodeType = { ELEMENT_NODE: 1, TEXT_NODE: 3, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_FRAGMENT_NODE: 11 }; var HTMLNodeType_1 = HTMLNodeType; var HostComponent$1 = ReactTypeOfWork.HostComponent; var HostText = ReactTypeOfWork.HostText; var ELEMENT_NODE = HTMLNodeType_1.ELEMENT_NODE; var COMMENT_NODE = HTMLNodeType_1.COMMENT_NODE; var ATTR_NAME = DOMProperty_1.ID_ATTRIBUTE_NAME; var Flags = ReactDOMComponentFlags_1; var randomKey = Math.random().toString(36).slice(2); var internalInstanceKey = '__reactInternalInstance$' + randomKey; var internalEventHandlersKey = '__reactEventHandlers$' + randomKey; /** * Check if a given node should be cached. */ function shouldPrecacheNode(node, nodeID) { return node.nodeType === ELEMENT_NODE && node.getAttribute(ATTR_NAME) === '' + nodeID || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-text: ' + nodeID + ' ' || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-empty: ' + nodeID + ' '; } /** * Drill down (through composites and empty components) until we get a host or * host text component. * * This is pretty polymorphic but unavoidable with the current structure we have * for `_renderedChildren`. */ function getRenderedHostOrTextFromComponent(component) { var rendered; while (rendered = component._renderedComponent) { component = rendered; } return component; } /** * Populate `_hostNode` on the rendered host/text component with the given * DOM node. The passed `inst` can be a composite. */ function precacheNode(inst, node) { var hostInst = getRenderedHostOrTextFromComponent(inst); hostInst._hostNode = node; node[internalInstanceKey] = hostInst; } function precacheFiberNode(hostInst, node) { node[internalInstanceKey] = hostInst; } function uncacheNode(inst) { var node = inst._hostNode; if (node) { delete node[internalInstanceKey]; inst._hostNode = null; } } /** * Populate `_hostNode` on each child of `inst`, assuming that the children * match up with the DOM (element) children of `node`. * * We cache entire levels at once to avoid an n^2 problem where we access the * children of a node sequentially and have to walk from the start to our target * node every time. * * Since we update `_renderedChildren` and the actual DOM at (slightly) * different times, we could race here and see a newer `_renderedChildren` than * the DOM nodes we see. To avoid this, ReactMultiChild calls * `prepareToManageChildren` before we change `_renderedChildren`, at which * time the container's child nodes are always cached (until it unmounts). */ function precacheChildNodes(inst, node) { if (inst._flags & Flags.hasCachedChildNodes) { return; } var children = inst._renderedChildren; var childNode = node.firstChild; outer: for (var name in children) { if (!children.hasOwnProperty(name)) { continue; } var childInst = children[name]; var childID = getRenderedHostOrTextFromComponent(childInst)._domID; if (childID === 0) { // We're currently unmounting this child in ReactMultiChild; skip it. continue; } // We assume the child nodes are in the same order as the child instances. for (; childNode !== null; childNode = childNode.nextSibling) { if (shouldPrecacheNode(childNode, childID)) { precacheNode(childInst, childNode); continue outer; } } // We reached the end of the DOM children without finding an ID match. invariant_1(false, 'Unable to find element with ID %s.', childID); } inst._flags |= Flags.hasCachedChildNodes; } /** * Given a DOM node, return the closest ReactDOMComponent or * ReactDOMTextComponent instance ancestor. */ function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } // Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; while (!node[internalInstanceKey]) { parents.push(node); if (node.parentNode) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var closest; var inst = node[internalInstanceKey]; if (inst.tag === HostComponent$1 || inst.tag === HostText) { // In Fiber, this will always be the deepest root. return inst; } for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) { closest = inst; if (parents.length) { precacheChildNodes(inst, node); } } return closest; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ function getInstanceFromNode(node) { var inst = node[internalInstanceKey]; if (inst) { if (inst.tag === HostComponent$1 || inst.tag === HostText) { return inst; } else if (inst._hostNode === node) { return inst; } else { return null; } } inst = getClosestInstanceFromNode(node); if (inst != null && inst._hostNode === node) { return inst; } else { return null; } } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ function getNodeFromInstance(inst) { if (inst.tag === HostComponent$1 || inst.tag === HostText) { // In Fiber this, is just the state node right now. We assume it will be // a host component or host text. return inst.stateNode; } // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. !(inst._hostNode !== undefined) ? invariant_1(false, 'getNodeFromInstance: Invalid argument.') : void 0; if (inst._hostNode) { return inst._hostNode; } // Walk up the tree until we find an ancestor whose DOM node we have cached. var parents = []; while (!inst._hostNode) { parents.push(inst); !inst._hostParent ? invariant_1(false, 'React DOM tree root should always have a node reference.') : void 0; inst = inst._hostParent; } // Now parents contains each ancestor that does *not* have a cached native // node, and `inst` is the deepest ancestor that does. for (; parents.length; inst = parents.pop()) { precacheChildNodes(inst, inst._hostNode); } return inst._hostNode; } function getFiberCurrentPropsFromNode(node) { return node[internalEventHandlersKey] || null; } function updateFiberProps(node, props) { node[internalEventHandlersKey] = props; } var ReactDOMComponentTree = { getClosestInstanceFromNode: getClosestInstanceFromNode, getInstanceFromNode: getInstanceFromNode, getNodeFromInstance: getNodeFromInstance, precacheChildNodes: precacheChildNodes, precacheNode: precacheNode, uncacheNode: uncacheNode, precacheFiberNode: precacheFiberNode, getFiberCurrentPropsFromNode: getFiberCurrentPropsFromNode, updateFiberProps: updateFiberProps }; var ReactDOMComponentTree_1 = ReactDOMComponentTree; // Used as a way to call batchedUpdates when we don't know if we're in a Fiber // or Stack context. Such as when we're dispatching events or if third party // libraries need to call batchedUpdates. Eventually, this API will go away when // everything is batched by default. We'll then have a similar API to opt-out of // scheduled work and instead do synchronous work. // Defaults var stackBatchedUpdates = function (fn, a, b, c, d, e) { return fn(a, b, c, d, e); }; var fiberBatchedUpdates = function (fn, bookkeeping) { return fn(bookkeeping); }; function performFiberBatchedUpdates(fn, bookkeeping) { // If we have Fiber loaded, we need to wrap this in a batching call so that // Fiber can apply its default priority for this call. return fiberBatchedUpdates(fn, bookkeeping); } function batchedUpdates(fn, bookkeeping) { // We first perform work with the stack batching strategy, by passing our // indirection to it. return stackBatchedUpdates(performFiberBatchedUpdates, fn, bookkeeping); } var isNestingBatched = false; function batchedUpdatesWithControlledComponents(fn, bookkeeping) { if (isNestingBatched) { // If we are currently inside another batch, we need to wait until it // fully completes before restoring state. Therefore, we add the target to // a queue of work. return batchedUpdates(fn, bookkeeping); } isNestingBatched = true; try { return batchedUpdates(fn, bookkeeping); } finally { // Here we wait until all updates have propagated, which is important // when using controlled components within layers: // https://github.com/facebook/react/issues/1698 // Then we restore state of any controlled component. isNestingBatched = false; ReactControlledComponent_1.restoreStateIfNeeded(); } } var ReactGenericBatchingInjection = { injectStackBatchedUpdates: function (_batchedUpdates) { stackBatchedUpdates = _batchedUpdates; }, injectFiberBatchedUpdates: function (_batchedUpdates) { fiberBatchedUpdates = _batchedUpdates; } }; var ReactGenericBatching = { batchedUpdates: batchedUpdatesWithControlledComponents, injection: ReactGenericBatchingInjection }; var ReactGenericBatching_1 = ReactGenericBatching; function isCheckable(elem) { var type = elem.type; var nodeName = elem.nodeName; return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio'); } function getTracker(inst) { if (typeof inst.tag === 'number') { inst = inst.stateNode; } return inst._wrapperState.valueTracker; } function attachTracker(inst, tracker) { inst._wrapperState.valueTracker = tracker; } function detachTracker(inst) { delete inst._wrapperState.valueTracker; } function getValueFromNode(node) { var value; if (node) { value = isCheckable(node) ? '' + node.checked : node.value; } return value; } function trackValueOnNode(node, inst) { var valueField = isCheckable(node) ? 'checked' : 'value'; var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail // and don't track value will cause over reporting of changes, // but it's better then a hard failure // (needed for certain tests that spyOn input values and Safari) if (node.hasOwnProperty(valueField) || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') { return; } Object.defineProperty(node, valueField, { enumerable: descriptor.enumerable, configurable: true, get: function () { return descriptor.get.call(this); }, set: function (value) { currentValue = '' + value; descriptor.set.call(this, value); } }); var tracker = { getValue: function () { return currentValue; }, setValue: function (value) { currentValue = '' + value; }, stopTracking: function () { detachTracker(inst); delete node[valueField]; } }; return tracker; } var inputValueTracking = { // exposed for testing _getTrackerFromNode: function (node) { return getTracker(ReactDOMComponentTree_1.getInstanceFromNode(node)); }, trackNode: function (node) { if (node._wrapperState.valueTracker) { return; } node._wrapperState.valueTracker = trackValueOnNode(node, node); }, track: function (inst) { if (getTracker(inst)) { return; } var node = ReactDOMComponentTree_1.getNodeFromInstance(inst); attachTracker(inst, trackValueOnNode(node, inst)); }, updateValueIfChanged: function (inst) { if (!inst) { return false; } var tracker = getTracker(inst); if (!tracker) { if (typeof inst.tag === 'number') { inputValueTracking.trackNode(inst.stateNode); } else { inputValueTracking.track(inst); } return true; } var lastValue = tracker.getValue(); var nextValue = getValueFromNode(ReactDOMComponentTree_1.getNodeFromInstance(inst)); if (nextValue !== lastValue) { tracker.setValue(nextValue); return true; } return false; }, stopTracking: function (inst) { var tracker = getTracker(inst); if (tracker) { tracker.stopTracking(); } } }; var inputValueTracking_1 = inputValueTracking; var TEXT_NODE = HTMLNodeType_1.TEXT_NODE; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963 if (target.correspondingUseElement) { target = target.correspondingUseElement; } // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === TEXT_NODE ? target.parentNode : target; } var getEventTarget_1 = getEventTarget; var useHasFeature; if (ExecutionEnvironment_1.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment_1.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } var isEventSupported_1 = isEventSupported; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextInputElement * */ /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { color: true, date: true, datetime: true, 'datetime-local': true, email: true, month: true, number: true, password: true, range: true, search: true, tel: true, text: true, time: true, url: true, week: true }; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); if (nodeName === 'input') { return !!supportedInputTypes[elem.type]; } if (nodeName === 'textarea') { return true; } return false; } var isTextInputElement_1 = isTextInputElement; var eventTypes$1 = { change: { phasedRegistrationNames: { bubbled: 'onChange', captured: 'onChangeCapture' }, dependencies: ['topBlur', 'topChange', 'topClick', 'topFocus', 'topInput', 'topKeyDown', 'topKeyUp', 'topSelectionChange'] } }; function createAndAccumulateChangeEvent(inst, nativeEvent, target) { var event = SyntheticEvent_1.getPooled(eventTypes$1.change, inst, nativeEvent, target); event.type = 'change'; // Flag this event loop as needing state restore. ReactControlledComponent_1.enqueueStateRestore(target); EventPropagators_1.accumulateTwoPhaseDispatches(event); return event; } /** * For IE shims */ var activeElement = null; var activeElementInst = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } function manualDispatchChangeEvent(nativeEvent) { var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget_1(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactGenericBatching_1.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub_1.enqueueEvents(event); EventPluginHub_1.processEventQueue(false); } function getInstIfValueChanged(targetInst) { if (inputValueTracking_1.updateValueIfChanged(targetInst)) { return targetInst; } } function getTargetInstForChangeEvent(topLevelType, targetInst) { if (topLevelType === 'topChange') { return targetInst; } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment_1.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events. isInputEventSupported = isEventSupported_1('input') && (!document.documentMode || document.documentMode > 9); } /** * (For IE <=9) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onpropertychange', handlePropertyChange); } /** * (For IE <=9) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementInst = null; } /** * (For IE <=9) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } if (getInstIfValueChanged(activeElementInst)) { manualDispatchChangeEvent(nativeEvent); } } function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) { if (topLevelType === 'topFocus') { // In IE9, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(target, targetInst); } else if (topLevelType === 'topBlur') { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetInstForInputEventPolyfill(topLevelType, targetInst) { if (topLevelType === 'topSelectionChange' || topLevelType === 'topKeyUp' || topLevelType === 'topKeyDown') { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. return getInstIfValueChanged(activeElementInst); } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. var nodeName = elem.nodeName; return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetInstForClickEvent(topLevelType, targetInst) { if (topLevelType === 'topClick') { return getInstIfValueChanged(targetInst); } } function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) { if (topLevelType === 'topInput' || topLevelType === 'topChange') { return getInstIfValueChanged(targetInst); } } function handleControlledInputBlur(inst, node) { // TODO: In IE, inst is occasionally null. Why? if (inst == null) { return; } // Fiber and ReactDOM keep wrapper state in separate places var state = inst._wrapperState || node._wrapperState; if (!state || !state.controlled || node.type !== 'number') { return; } // If controlled, assign the value attribute to the current value on blur var value = '' + node.value; if (node.getAttribute('value') !== value) { node.setAttribute('value', value); } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes$1, _isInputEventSupported: isInputEventSupported, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var targetNode = targetInst ? ReactDOMComponentTree_1.getNodeFromInstance(targetInst) : window; var getTargetInstFunc, handleEventFunc; if (shouldUseChangeEvent(targetNode)) { getTargetInstFunc = getTargetInstForChangeEvent; } else if (isTextInputElement_1(targetNode)) { if (isInputEventSupported) { getTargetInstFunc = getTargetInstForInputOrChangeEvent; } else { getTargetInstFunc = getTargetInstForInputEventPolyfill; handleEventFunc = handleEventsForInputEventPolyfill; } } else if (shouldUseClickEvent(targetNode)) { getTargetInstFunc = getTargetInstForClickEvent; } if (getTargetInstFunc) { var inst = getTargetInstFunc(topLevelType, targetInst); if (inst) { var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget); return event; } } if (handleEventFunc) { handleEventFunc(topLevelType, targetNode, targetInst); } // When blurring, set the value attribute for number inputs if (topLevelType === 'topBlur') { handleControlledInputBlur(targetInst, targetNode); } } }; var ChangeEventPlugin_1 = ChangeEventPlugin; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMEventPluginOrder */ /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'TapEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin']; var DOMEventPluginOrder_1 = DOMEventPluginOrder; /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function (event) { if (event.view) { return event.view; } var target = getEventTarget_1(event); if (target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function (event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent_1.augmentClass(SyntheticUIEvent, UIEventInterface); var SyntheticUIEvent_1 = SyntheticUIEvent; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventModifierState */ /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { Alt: 'altKey', Control: 'ctrlKey', Meta: 'metaKey', Shift: 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } var getEventModifierState_1 = getEventModifierState; /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, pageX: null, pageY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState_1, button: null, buttons: null, relatedTarget: function (event) { return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent_1.augmentClass(SyntheticMouseEvent, MouseEventInterface); var SyntheticMouseEvent_1 = SyntheticMouseEvent; var eventTypes$2 = { mouseEnter: { registrationName: 'onMouseEnter', dependencies: ['topMouseOut', 'topMouseOver'] }, mouseLeave: { registrationName: 'onMouseLeave', dependencies: ['topMouseOut', 'topMouseOver'] } }; var EnterLeaveEventPlugin = { eventTypes: eventTypes$2, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (topLevelType === 'topMouseOver' && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== 'topMouseOut' && topLevelType !== 'topMouseOver') { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; if (topLevelType === 'topMouseOut') { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? ReactDOMComponentTree_1.getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromNode = from == null ? win : ReactDOMComponentTree_1.getNodeFromInstance(from); var toNode = to == null ? win : ReactDOMComponentTree_1.getNodeFromInstance(to); var leave = SyntheticMouseEvent_1.getPooled(eventTypes$2.mouseLeave, from, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = fromNode; leave.relatedTarget = toNode; var enter = SyntheticMouseEvent_1.getPooled(eventTypes$2.mouseEnter, to, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = toNode; enter.relatedTarget = fromNode; EventPropagators_1.accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; } }; var EnterLeaveEventPlugin_1 = EnterLeaveEventPlugin; var MUST_USE_PROPERTY = DOMProperty_1.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty_1.injection.HAS_BOOLEAN_VALUE; var HAS_NUMERIC_VALUE = DOMProperty_1.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty_1.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty_1.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty_1.ATTRIBUTE_NAME_CHAR + ']*$')), Properties: { /** * Standard Properties */ accept: 0, acceptCharset: 0, accessKey: 0, action: 0, allowFullScreen: HAS_BOOLEAN_VALUE, allowTransparency: 0, alt: 0, // specifies target context for links with `preload` type as: 0, async: HAS_BOOLEAN_VALUE, autoComplete: 0, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: HAS_BOOLEAN_VALUE, cellPadding: 0, cellSpacing: 0, charSet: 0, challenge: 0, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, cite: 0, classID: 0, className: 0, cols: HAS_POSITIVE_NUMERIC_VALUE, colSpan: 0, content: 0, contentEditable: 0, contextMenu: 0, controls: HAS_BOOLEAN_VALUE, coords: 0, crossOrigin: 0, data: 0, // For `<object />` acts as `src`. dateTime: 0, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: 0, disabled: HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: 0, encType: 0, form: 0, formAction: 0, formEncType: 0, formMethod: 0, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: 0, frameBorder: 0, headers: 0, height: 0, hidden: HAS_BOOLEAN_VALUE, high: 0, href: 0, hrefLang: 0, htmlFor: 0, httpEquiv: 0, id: 0, inputMode: 0, integrity: 0, is: 0, keyParams: 0, keyType: 0, kind: 0, label: 0, lang: 0, list: 0, loop: HAS_BOOLEAN_VALUE, low: 0, manifest: 0, marginHeight: 0, marginWidth: 0, max: 0, maxLength: 0, media: 0, mediaGroup: 0, method: 0, min: 0, minLength: 0, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: 0, nonce: 0, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: 0, pattern: 0, placeholder: 0, playsInline: HAS_BOOLEAN_VALUE, poster: 0, preload: 0, profile: 0, radioGroup: 0, readOnly: HAS_BOOLEAN_VALUE, referrerPolicy: 0, rel: 0, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: 0, rows: HAS_POSITIVE_NUMERIC_VALUE, rowSpan: HAS_NUMERIC_VALUE, sandbox: 0, scope: 0, scoped: HAS_BOOLEAN_VALUE, scrolling: 0, seamless: HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: 0, size: HAS_POSITIVE_NUMERIC_VALUE, sizes: 0, // support for projecting regular DOM Elements via V1 named slots ( shadow dom ) slot: 0, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: 0, src: 0, srcDoc: 0, srcLang: 0, srcSet: 0, start: HAS_NUMERIC_VALUE, step: 0, style: 0, summary: 0, tabIndex: 0, target: 0, title: 0, // Setting .type throws on non-<input> tags type: 0, useMap: 0, value: 0, width: 0, wmode: 0, wrap: 0, /** * RDFa Properties */ about: 0, datatype: 0, inlist: 0, prefix: 0, // property is also supported for OpenGraph in meta tags. property: 0, resource: 0, 'typeof': 0, vocab: 0, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: 0, autoCorrect: 0, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: 0, // color is for Safari mask-icon link color: 0, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: 0, itemScope: HAS_BOOLEAN_VALUE, itemType: 0, // itemID and itemRef are for Microdata support as well but // only specified in the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: 0, itemRef: 0, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: 0, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: 0, // IE-only attribute that controls focus behavior unselectable: 0 }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: {}, DOMMutationMethods: { value: function (node, value) { if (value == null) { return node.removeAttribute('value'); } // Number inputs get special treatment due to some edge cases in // Chrome. Let everything else assign the value attribute as normal. // https://github.com/facebook/react/issues/7253#issuecomment-236074326 if (node.type !== 'number' || node.hasAttribute('value') === false) { node.setAttribute('value', '' + value); } else if (node.validity && !node.validity.badInput && node.ownerDocument.activeElement !== node) { // Don't assign an attribute if validation reports bad // input. Chrome will clear the value. Additionally, don't // operate on inputs that have focus, otherwise Chrome might // strip off trailing decimal places and cause the user's // cursor position to jump to the beginning of the input. // // In ReactDOMInput, we have an onBlur event that will trigger // this function again when focus is lost. node.setAttribute('value', '' + value); } } } }; var HTMLDOMPropertyConfig_1 = HTMLDOMPropertyConfig; function runEventQueueInBatch(events) { EventPluginHub_1.enqueueEvents(events); EventPluginHub_1.processEventQueue(false); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. */ handleTopLevel: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events = EventPluginHub_1.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); runEventQueueInBatch(events); } }; var ReactEventEmitterMixin_1 = ReactEventEmitterMixin; /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; prefixes['ms' + styleProp] = 'MS' + eventName; prefixes['O' + styleProp] = 'o' + eventName.toLowerCase(); return prefixes; } /** * A list of event names to a configurable list of vendor prefixes. */ var vendorPrefixes = { animationend: makePrefixMap('Animation', 'AnimationEnd'), animationiteration: makePrefixMap('Animation', 'AnimationIteration'), animationstart: makePrefixMap('Animation', 'AnimationStart'), transitionend: makePrefixMap('Transition', 'TransitionEnd') }; /** * Event names that have already been detected and prefixed (if applicable). */ var prefixedEventNames = {}; /** * Element to check for prefixes on. */ var style = {}; /** * Bootstrap if a DOM exists. */ if (ExecutionEnvironment_1.canUseDOM) { style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are usable, and if not remove them from the map. if (!('AnimationEvent' in window)) { delete vendorPrefixes.animationend.animation; delete vendorPrefixes.animationiteration.animation; delete vendorPrefixes.animationstart.animation; } // Same as above if (!('TransitionEvent' in window)) { delete vendorPrefixes.transitionend.transition; } } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return ''; } var getVendorPrefixedEventName_1 = getVendorPrefixedEventName; /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var alreadyListeningTo = {}; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topAbort: 'abort', topAnimationEnd: getVendorPrefixedEventName_1('animationend') || 'animationend', topAnimationIteration: getVendorPrefixedEventName_1('animationiteration') || 'animationiteration', topAnimationStart: getVendorPrefixedEventName_1('animationstart') || 'animationstart', topBlur: 'blur', topCancel: 'cancel', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topChange: 'change', topClick: 'click', topClose: 'close', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topScroll: 'scroll', topSeeked: 'seeked', topSeeking: 'seeking', topSelectionChange: 'selectionchange', topStalled: 'stalled', topSuspend: 'suspend', topTextInput: 'textInput', topTimeUpdate: 'timeupdate', topToggle: 'toggle', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topTransitionEnd: getVendorPrefixedEventName_1('transitionend') || 'transitionend', topVolumeChange: 'volumechange', topWaiting: 'waiting', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + ('' + Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } var ReactBrowserEventEmitter = index({}, ReactEventEmitterMixin_1, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function (ReactEventListener) { ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function (enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function () { return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function (registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry_1.registrationNameDependencies[registrationName]; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { if (dependency === 'topWheel') { if (isEventSupported_1('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'wheel', mountAt); } else if (isEventSupported_1('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'DOMMouseScroll', mountAt); } } else if (dependency === 'topScroll') { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topScroll', 'scroll', mountAt); } else if (dependency === 'topFocus' || dependency === 'topBlur') { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topFocus', 'focus', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topBlur', 'blur', mountAt); // to make sure blur and focus event listeners are only attached once isListening.topBlur = true; isListening.topFocus = true; } else if (dependency === 'topCancel') { if (isEventSupported_1('cancel', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topCancel', 'cancel', mountAt); } isListening.topCancel = true; } else if (dependency === 'topClose') { if (isEventSupported_1('close', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topClose', 'close', mountAt); } isListening.topClose = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, isListeningToAllDependencies: function (registrationName, mountAt) { var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry_1.registrationNameDependencies[registrationName]; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { return false; } } return true; }, trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); }, trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); } }); var ReactBrowserEventEmitter_1 = ReactBrowserEventEmitter; /** * Copyright (c) 2013-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @typechecks */ /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function listen(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function remove() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function remove() { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function capture(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, true); return { remove: function remove() { target.removeEventListener(eventType, callback, true); } }; } else { { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction_1 }; } }, registerDefault: function registerDefault() {} }; var EventListener_1 = EventListener; /** * 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 */ /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable.Window && scrollable instanceof scrollable.Window) { return { x: scrollable.pageXOffset || scrollable.document.documentElement.scrollLeft, y: scrollable.pageYOffset || scrollable.document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } var getUnboundedScrollPosition_1 = getUnboundedScrollPosition; var HostRoot = ReactTypeOfWork.HostRoot; /** * Find the deepest React component completely containing the root of the * passed-in instance (for use when entire React trees are nested within each * other). If React trees are not nested, returns null. */ function findRootContainerNode(inst) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. if (typeof inst.tag === 'number') { while (inst['return']) { inst = inst['return']; } if (inst.tag !== HostRoot) { // This can happen if we're in a detached tree. return null; } return inst.stateNode.containerInfo; } else { while (inst._hostParent) { inst = inst._hostParent; } var rootNode = ReactDOMComponentTree_1.getNodeFromInstance(inst); return rootNode.parentNode; } } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.targetInst = targetInst; this.ancestors = []; } index(TopLevelCallbackBookKeeping.prototype, { destructor: function () { this.topLevelType = null; this.nativeEvent = null; this.targetInst = null; this.ancestors.length = 0; } }); PooledClass_1.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass_1.threeArgumentPooler); function handleTopLevelImpl(bookKeeping) { var targetInst = bookKeeping.targetInst; // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = targetInst; do { if (!ancestor) { bookKeeping.ancestors.push(ancestor); break; } var root = findRootContainerNode(ancestor); if (!root) { break; } bookKeeping.ancestors.push(ancestor); ancestor = ReactDOMComponentTree_1.getClosestInstanceFromNode(root); } while (ancestor); for (var i = 0; i < bookKeeping.ancestors.length; i++) { targetInst = bookKeeping.ancestors[i]; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget_1(bookKeeping.nativeEvent)); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition_1(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, setHandleTopLevel: function (handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function (enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function () { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} element Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function (topLevelType, handlerBaseName, element) { if (!element) { return null; } return EventListener_1.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} element Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function (topLevelType, handlerBaseName, element) { if (!element) { return null; } return EventListener_1.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, monitorScrollValue: function (refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener_1.listen(window, 'scroll', callback); }, dispatchEvent: function (topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var nativeEventTarget = getEventTarget_1(nativeEvent); var targetInst = ReactDOMComponentTree_1.getClosestInstanceFromNode(nativeEventTarget); var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent, targetInst); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactGenericBatching_1.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; var ReactEventListener_1 = ReactEventListener; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SVGDOMPropertyConfig */ var NS = { xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; // We use attributes for everything SVG so let's avoid some duplication and run // code instead. // The following are all specified in the HTML config already so we exclude here. // - class (as className) // - color // - height // - id // - lang // - max // - media // - method // - min // - name // - style // - target // - type // - width var ATTRS = { accentHeight: 'accent-height', accumulate: 0, additive: 0, alignmentBaseline: 'alignment-baseline', allowReorder: 'allowReorder', alphabetic: 0, amplitude: 0, arabicForm: 'arabic-form', ascent: 0, attributeName: 'attributeName', attributeType: 'attributeType', autoReverse: 'autoReverse', azimuth: 0, baseFrequency: 'baseFrequency', baseProfile: 'baseProfile', baselineShift: 'baseline-shift', bbox: 0, begin: 0, bias: 0, by: 0, calcMode: 'calcMode', capHeight: 'cap-height', clip: 0, clipPath: 'clip-path', clipRule: 'clip-rule', clipPathUnits: 'clipPathUnits', colorInterpolation: 'color-interpolation', colorInterpolationFilters: 'color-interpolation-filters', colorProfile: 'color-profile', colorRendering: 'color-rendering', contentScriptType: 'contentScriptType', contentStyleType: 'contentStyleType', cursor: 0, cx: 0, cy: 0, d: 0, decelerate: 0, descent: 0, diffuseConstant: 'diffuseConstant', direction: 0, display: 0, divisor: 0, dominantBaseline: 'dominant-baseline', dur: 0, dx: 0, dy: 0, edgeMode: 'edgeMode', elevation: 0, enableBackground: 'enable-background', end: 0, exponent: 0, externalResourcesRequired: 'externalResourcesRequired', fill: 0, fillOpacity: 'fill-opacity', fillRule: 'fill-rule', filter: 0, filterRes: 'filterRes', filterUnits: 'filterUnits', floodColor: 'flood-color', floodOpacity: 'flood-opacity', focusable: 0, fontFamily: 'font-family', fontSize: 'font-size', fontSizeAdjust: 'font-size-adjust', fontStretch: 'font-stretch', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', format: 0, from: 0, fx: 0, fy: 0, g1: 0, g2: 0, glyphName: 'glyph-name', glyphOrientationHorizontal: 'glyph-orientation-horizontal', glyphOrientationVertical: 'glyph-orientation-vertical', glyphRef: 'glyphRef', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', hanging: 0, horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x', ideographic: 0, imageRendering: 'image-rendering', 'in': 0, in2: 0, intercept: 0, k: 0, k1: 0, k2: 0, k3: 0, k4: 0, kernelMatrix: 'kernelMatrix', kernelUnitLength: 'kernelUnitLength', kerning: 0, keyPoints: 'keyPoints', keySplines: 'keySplines', keyTimes: 'keyTimes', lengthAdjust: 'lengthAdjust', letterSpacing: 'letter-spacing', lightingColor: 'lighting-color', limitingConeAngle: 'limitingConeAngle', local: 0, markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', markerHeight: 'markerHeight', markerUnits: 'markerUnits', markerWidth: 'markerWidth', mask: 0, maskContentUnits: 'maskContentUnits', maskUnits: 'maskUnits', mathematical: 0, mode: 0, numOctaves: 'numOctaves', offset: 0, opacity: 0, operator: 0, order: 0, orient: 0, orientation: 0, origin: 0, overflow: 0, overlinePosition: 'overline-position', overlineThickness: 'overline-thickness', paintOrder: 'paint-order', panose1: 'panose-1', pathLength: 'pathLength', patternContentUnits: 'patternContentUnits', patternTransform: 'patternTransform', patternUnits: 'patternUnits', pointerEvents: 'pointer-events', points: 0, pointsAtX: 'pointsAtX', pointsAtY: 'pointsAtY', pointsAtZ: 'pointsAtZ', preserveAlpha: 'preserveAlpha', preserveAspectRatio: 'preserveAspectRatio', primitiveUnits: 'primitiveUnits', r: 0, radius: 0, refX: 'refX', refY: 'refY', renderingIntent: 'rendering-intent', repeatCount: 'repeatCount', repeatDur: 'repeatDur', requiredExtensions: 'requiredExtensions', requiredFeatures: 'requiredFeatures', restart: 0, result: 0, rotate: 0, rx: 0, ry: 0, scale: 0, seed: 0, shapeRendering: 'shape-rendering', slope: 0, spacing: 0, specularConstant: 'specularConstant', specularExponent: 'specularExponent', speed: 0, spreadMethod: 'spreadMethod', startOffset: 'startOffset', stdDeviation: 'stdDeviation', stemh: 0, stemv: 0, stitchTiles: 'stitchTiles', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strikethroughPosition: 'strikethrough-position', strikethroughThickness: 'strikethrough-thickness', string: 0, stroke: 0, strokeDasharray: 'stroke-dasharray', strokeDashoffset: 'stroke-dashoffset', strokeLinecap: 'stroke-linecap', strokeLinejoin: 'stroke-linejoin', strokeMiterlimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', surfaceScale: 'surfaceScale', systemLanguage: 'systemLanguage', tableValues: 'tableValues', targetX: 'targetX', targetY: 'targetY', textAnchor: 'text-anchor', textDecoration: 'text-decoration', textRendering: 'text-rendering', textLength: 'textLength', to: 0, transform: 0, u1: 0, u2: 0, underlinePosition: 'underline-position', underlineThickness: 'underline-thickness', unicode: 0, unicodeBidi: 'unicode-bidi', unicodeRange: 'unicode-range', unitsPerEm: 'units-per-em', vAlphabetic: 'v-alphabetic', vHanging: 'v-hanging', vIdeographic: 'v-ideographic', vMathematical: 'v-mathematical', values: 0, vectorEffect: 'vector-effect', version: 0, vertAdvY: 'vert-adv-y', vertOriginX: 'vert-origin-x', vertOriginY: 'vert-origin-y', viewBox: 'viewBox', viewTarget: 'viewTarget', visibility: 0, widths: 0, wordSpacing: 'word-spacing', writingMode: 'writing-mode', x: 0, xHeight: 'x-height', x1: 0, x2: 0, xChannelSelector: 'xChannelSelector', xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlns: 0, xmlnsXlink: 'xmlns:xlink', xmlLang: 'xml:lang', xmlSpace: 'xml:space', y: 0, y1: 0, y2: 0, yChannelSelector: 'yChannelSelector', z: 0, zoomAndPan: 'zoomAndPan' }; var SVGDOMPropertyConfig = { Properties: {}, DOMAttributeNamespaces: { xlinkActuate: NS.xlink, xlinkArcrole: NS.xlink, xlinkHref: NS.xlink, xlinkRole: NS.xlink, xlinkShow: NS.xlink, xlinkTitle: NS.xlink, xlinkType: NS.xlink, xmlBase: NS.xml, xmlLang: NS.xml, xmlSpace: NS.xml }, DOMAttributeNames: {} }; Object.keys(ATTRS).forEach(function (key) { SVGDOMPropertyConfig.Properties[key] = 0; if (ATTRS[key]) { SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key]; } }); var SVGDOMPropertyConfig_1 = SVGDOMPropertyConfig; var TEXT_NODE$1 = HTMLNodeType_1.TEXT_NODE; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === TEXT_NODE$1) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } var getNodeForCharacterOffset_1 = getNodeForCharacterOffset; /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); // In Firefox, range.startContainer and range.endContainer can be "anonymous // divs", e.g. the up/down buttons on an <input type="number">. Anonymous // divs do not seem to expose properties, triggering a "Permission denied // error" if any of its properties are accessed. The only seemingly possible // way to avoid erroring is to access a property that typically works for // non-anonymous divs and catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ currentRange.startContainer.nodeType; currentRange.endContainer.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programmatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor_1()].length; var start = Math.min(offsets.start, length); var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset_1(node, start); var endMarker = getNodeForCharacterOffset_1(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: setModernOffsets }; var ReactDOMSelection_1 = ReactDOMSelection; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { var doc = object ? object.ownerDocument || object : document; var defaultView = doc.defaultView || window; return !!(object && (typeof defaultView.Node === 'function' ? object instanceof defaultView.Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } var isNode_1 = isNode; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode_1(object) && object.nodeType == 3; } var isTextNode_1 = isTextNode; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ /*eslint-disable no-bitwise */ /** * Checks if a given DOM node contains or is another DOM node. */ function containsNode(outerNode, innerNode) { if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode_1(outerNode)) { return false; } else if (isTextNode_1(innerNode)) { return containsNode(outerNode, innerNode.parentNode); } else if ('contains' in outerNode) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } var containsNode_1 = containsNode; /** * 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. * */ /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch (e) {} } var focusNode_1 = focusNode; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /* eslint-disable fb-www/typeof-undefined */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document or document body is not * yet defined. * * @param {?DOMDocument} doc Defaults to current document. * @return {?DOMElement} */ function getActiveElement(doc) /*?DOMElement*/{ doc = doc || (typeof document !== 'undefined' ? document : undefined); if (typeof doc === 'undefined') { return null; } try { return doc.activeElement || doc.body; } catch (e) { return doc.body; } } var getActiveElement_1 = getActiveElement; var ELEMENT_NODE$1 = HTMLNodeType_1.ELEMENT_NODE; function isInDocument(node) { return containsNode_1(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function (elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); }, getSelectionInformation: function () { var focusedElem = getActiveElement_1(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function (priorSelectionInformation) { var curFocusedElem = getActiveElement_1(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); } // Focusing a node can change the scroll position, which is undesirable var ancestors = []; var ancestor = priorFocusedElem; while (ancestor = ancestor.parentNode) { if (ancestor.nodeType === ELEMENT_NODE$1) { ancestors.push({ element: ancestor, left: ancestor.scrollLeft, top: ancestor.scrollTop }); } } focusNode_1(priorFocusedElem); for (var i = 0; i < ancestors.length; i++) { var info = ancestors[i]; info.element.scrollLeft = info.left; info.element.scrollTop = info.top; } } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function (input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else { // Content editable or old IE textarea. selection = ReactDOMSelection_1.getOffsets(input); } return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function (input, offsets) { var start = offsets.start; var end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else { ReactDOMSelection_1.setOffsets(input, offsets); } } }; var ReactInputSelection_1 = ReactInputSelection; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * */ /*eslint-disable no-self-compare */ var hasOwnProperty$1 = Object.prototype.hasOwnProperty; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 // Added the nonzero y check to make Flow happy, but it is redundant return x !== 0 || y !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (is(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if (!hasOwnProperty$1.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } var shallowEqual_1 = shallowEqual; var DOCUMENT_NODE = HTMLNodeType_1.DOCUMENT_NODE; var skipSelectionChangeEvent = ExecutionEnvironment_1.canUseDOM && 'documentMode' in document && document.documentMode <= 11; var eventTypes$3 = { select: { phasedRegistrationNames: { bubbled: 'onSelect', captured: 'onSelectCapture' }, dependencies: ['topBlur', 'topContextMenu', 'topFocus', 'topKeyDown', 'topKeyUp', 'topMouseDown', 'topMouseUp', 'topSelectionChange'] } }; var activeElement$1 = null; var activeElementInst$1 = null; var lastSelection = null; var mouseDown = false; // Track whether all listeners exists for this plugin. If none exist, we do // not extract events. See #3639. var isListeningToAllDependencies = ReactBrowserEventEmitter_1.isListeningToAllDependencies; /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @return {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection_1.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement_1()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement$1); if (!lastSelection || !shallowEqual_1(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent_1.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement$1; EventPropagators_1.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes$3, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var doc = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget.document : nativeEventTarget.nodeType === DOCUMENT_NODE ? nativeEventTarget : nativeEventTarget.ownerDocument; if (!doc || !isListeningToAllDependencies('onSelect', doc)) { return null; } var targetNode = targetInst ? ReactDOMComponentTree_1.getNodeFromInstance(targetInst) : window; switch (topLevelType) { // Track the input node that has focus. case 'topFocus': if (isTextInputElement_1(targetNode) || targetNode.contentEditable === 'true') { activeElement$1 = targetNode; activeElementInst$1 = targetInst; lastSelection = null; } break; case 'topBlur': activeElement$1 = null; activeElementInst$1 = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case 'topMouseDown': mouseDown = true; break; case 'topContextMenu': case 'topMouseUp': mouseDown = false; return constructSelectEvent(nativeEvent, nativeEventTarget); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case 'topSelectionChange': if (skipSelectionChangeEvent) { break; } // falls through case 'topKeyDown': case 'topKeyUp': return constructSelectEvent(nativeEvent, nativeEventTarget); } return null; } }; var SelectEventPlugin_1 = SelectEventPlugin; /** * @interface Event * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent */ var AnimationEventInterface = { animationName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent_1.augmentClass(SyntheticAnimationEvent, AnimationEventInterface); var SyntheticAnimationEvent_1 = SyntheticAnimationEvent; /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function (event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent_1.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); var SyntheticClipboardEvent_1 = SyntheticClipboardEvent; /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent_1.augmentClass(SyntheticFocusEvent, FocusEventInterface); var SyntheticFocusEvent_1 = SyntheticFocusEvent; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventCharCode */ /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } var getEventCharCode_1 = getEventCharCode; /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { Esc: 'Escape', Spacebar: ' ', Left: 'ArrowLeft', Up: 'ArrowUp', Right: 'ArrowRight', Down: 'ArrowDown', Del: 'Delete', Win: 'OS', Menu: 'ContextMenu', Apps: 'ContextMenu', Scroll: 'ScrollLock', MozPrintableKey: 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { 8: 'Backspace', 9: 'Tab', 12: 'Clear', 13: 'Enter', 16: 'Shift', 17: 'Control', 18: 'Alt', 19: 'Pause', 20: 'CapsLock', 27: 'Escape', 32: ' ', 33: 'PageUp', 34: 'PageDown', 35: 'End', 36: 'Home', 37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 45: 'Insert', 46: 'Delete', 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6', 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12', 144: 'NumLock', 145: 'ScrollLock', 224: 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode_1(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } var getEventKey_1 = getEventKey; /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey_1, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState_1, // Legacy Interface charCode: function (event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode_1(event); } return 0; }, keyCode: function (event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function (event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode_1(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent_1.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); var SyntheticKeyboardEvent_1 = SyntheticKeyboardEvent; /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent_1.augmentClass(SyntheticDragEvent, DragEventInterface); var SyntheticDragEvent_1 = SyntheticDragEvent; /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState_1 }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent_1.augmentClass(SyntheticTouchEvent, TouchEventInterface); var SyntheticTouchEvent_1 = SyntheticTouchEvent; /** * @interface Event * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events- * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent */ var TransitionEventInterface = { propertyName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent_1.augmentClass(SyntheticTransitionEvent, TransitionEventInterface); var SyntheticTransitionEvent_1 = SyntheticTransitionEvent; /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function (event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY: function (event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent_1.augmentClass(SyntheticWheelEvent, WheelEventInterface); var SyntheticWheelEvent_1 = SyntheticWheelEvent; /** * Turns * ['abort', ...] * into * eventTypes = { * 'abort': { * phasedRegistrationNames: { * bubbled: 'onAbort', * captured: 'onAbortCapture', * }, * dependencies: ['topAbort'], * }, * ... * }; * topLevelEventsToDispatchConfig = { * 'topAbort': { sameConfig } * }; */ var eventTypes$4 = {}; var topLevelEventsToDispatchConfig = {}; ['abort', 'animationEnd', 'animationIteration', 'animationStart', 'blur', 'cancel', 'canPlay', 'canPlayThrough', 'click', 'close', 'contextMenu', 'copy', 'cut', 'doubleClick', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'focus', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'mouseDown', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp', 'paste', 'pause', 'play', 'playing', 'progress', 'rateChange', 'reset', 'scroll', 'seeked', 'seeking', 'stalled', 'submit', 'suspend', 'timeUpdate', 'toggle', 'touchCancel', 'touchEnd', 'touchMove', 'touchStart', 'transitionEnd', 'volumeChange', 'waiting', 'wheel'].forEach(function (event) { var capitalizedEvent = event[0].toUpperCase() + event.slice(1); var onEvent = 'on' + capitalizedEvent; var topEvent = 'top' + capitalizedEvent; var type = { phasedRegistrationNames: { bubbled: onEvent, captured: onEvent + 'Capture' }, dependencies: [topEvent] }; eventTypes$4[event] = type; topLevelEventsToDispatchConfig[topEvent] = type; }); var SimpleEventPlugin = { eventTypes: eventTypes$4, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case 'topAbort': case 'topCancel': case 'topCanPlay': case 'topCanPlayThrough': case 'topClose': case 'topDurationChange': case 'topEmptied': case 'topEncrypted': case 'topEnded': case 'topError': case 'topInput': case 'topInvalid': case 'topLoad': case 'topLoadedData': case 'topLoadedMetadata': case 'topLoadStart': case 'topPause': case 'topPlay': case 'topPlaying': case 'topProgress': case 'topRateChange': case 'topReset': case 'topSeeked': case 'topSeeking': case 'topStalled': case 'topSubmit': case 'topSuspend': case 'topTimeUpdate': case 'topToggle': case 'topVolumeChange': case 'topWaiting': // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent_1; break; case 'topKeyPress': // Firefox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode_1(nativeEvent) === 0) { return null; } /* falls through */ case 'topKeyDown': case 'topKeyUp': EventConstructor = SyntheticKeyboardEvent_1; break; case 'topBlur': case 'topFocus': EventConstructor = SyntheticFocusEvent_1; break; case 'topClick': // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case 'topDoubleClick': case 'topMouseDown': case 'topMouseMove': case 'topMouseUp': // TODO: Disabled elements should not respond to mouse events /* falls through */ case 'topMouseOut': case 'topMouseOver': case 'topContextMenu': EventConstructor = SyntheticMouseEvent_1; break; case 'topDrag': case 'topDragEnd': case 'topDragEnter': case 'topDragExit': case 'topDragLeave': case 'topDragOver': case 'topDragStart': case 'topDrop': EventConstructor = SyntheticDragEvent_1; break; case 'topTouchCancel': case 'topTouchEnd': case 'topTouchMove': case 'topTouchStart': EventConstructor = SyntheticTouchEvent_1; break; case 'topAnimationEnd': case 'topAnimationIteration': case 'topAnimationStart': EventConstructor = SyntheticAnimationEvent_1; break; case 'topTransitionEnd': EventConstructor = SyntheticTransitionEvent_1; break; case 'topScroll': EventConstructor = SyntheticUIEvent_1; break; case 'topWheel': EventConstructor = SyntheticWheelEvent_1; break; case 'topCopy': case 'topCut': case 'topPaste': EventConstructor = SyntheticClipboardEvent_1; break; } !EventConstructor ? invariant_1(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : void 0; var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget); EventPropagators_1.accumulateTwoPhaseDispatches(event); return event; } }; var SimpleEventPlugin_1 = SimpleEventPlugin; var alreadyInjected = false; function inject() { if (alreadyInjected) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected = true; ReactBrowserEventEmitter_1.injection.injectReactEventListener(ReactEventListener_1); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ EventPluginHub_1.injection.injectEventPluginOrder(DOMEventPluginOrder_1); EventPluginUtils_1.injection.injectComponentTree(ReactDOMComponentTree_1); /** * Some important event plugins included by default (without having to require * them). */ EventPluginHub_1.injection.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin_1, EnterLeaveEventPlugin: EnterLeaveEventPlugin_1, ChangeEventPlugin: ChangeEventPlugin_1, SelectEventPlugin: SelectEventPlugin_1, BeforeInputEventPlugin: BeforeInputEventPlugin_1 }); DOMProperty_1.injection.injectDOMPropertyConfig(ARIADOMPropertyConfig_1); DOMProperty_1.injection.injectDOMPropertyConfig(HTMLDOMPropertyConfig_1); DOMProperty_1.injection.injectDOMPropertyConfig(SVGDOMPropertyConfig_1); } var ReactDOMInjection = { inject: inject }; 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 ? invariant_1(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : void 0; ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; var ReactComponentEnvironment_1 = ReactComponentEnvironment; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMNamespaces */ var DOMNamespaces = { html: 'http://www.w3.org/1999/xhtml', mathml: 'http://www.w3.org/1998/Math/MathML', svg: 'http://www.w3.org/2000/svg' }; var DOMNamespaces_1 = DOMNamespaces; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createMicrosoftUnsafeLocalFunction */ /* globals MSApp */ /** * Create a function which has 'unsafe' privileges (required by windows8 apps) */ var createMicrosoftUnsafeLocalFunction = function (func) { if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { return function (arg0, arg1, arg2, arg3) { MSApp.execUnsafeLocalFunction(function () { return func(arg0, arg1, arg2, arg3); }); }; } else { return func; } }; var createMicrosoftUnsafeLocalFunction_1 = createMicrosoftUnsafeLocalFunction; // SVG temp container for IE lacking innerHTML var reusableSVGContainer; /** * Set the innerHTML property of a node * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = createMicrosoftUnsafeLocalFunction_1(function (node, html) { // IE does not have innerHTML for SVG nodes, so instead we inject the // new markup in a temp node and then move the child nodes across into // the target node if (node.namespaceURI === DOMNamespaces_1.svg && !('innerHTML' in node)) { reusableSVGContainer = reusableSVGContainer || document.createElement('div'); reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>'; var svgNode = reusableSVGContainer.firstChild; while (svgNode.firstChild) { node.appendChild(svgNode.firstChild); } } else { node.innerHTML = html; } }); var setInnerHTML_1 = setInnerHTML; /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * Based on the escape-html library, which is used under the MIT License below: * * Copyright (c) 2012-2013 TJ Holowaychuk * Copyright (c) 2015 Andreas Lubbe * Copyright (c) 2015 Tiancheng "Timothy" Gu * * 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. * * @providesModule escapeTextContentForBrowser */ // code copied and modified from escape-html /** * Module variables. * @private */ var matchHtmlRegExp = /["'&<>]/; /** * Escape special characters in the given string of html. * * @param {string} string The string to escape for inserting into HTML * @return {string} * @public */ function escapeHtml(string) { var str = '' + string; var match = matchHtmlRegExp.exec(str); if (!match) { return str; } var escape; var html = ''; var index = 0; var lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '&quot;'; break; case 38: // & escape = '&amp;'; break; case 39: // ' escape = '&#x27;'; // modified from escape-html; used to be '&#39' break; case 60: // < escape = '&lt;'; break; case 62: // > escape = '&gt;'; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escape; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; } // end code copied and modified from escape-html /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { if (typeof text === 'boolean' || typeof text === 'number') { // this shortcircuit helps perf for types that we know will never have // special characters, especially given that this function is used often // for numeric dom ids. return '' + text; } return escapeHtml(text); } var escapeTextContentForBrowser_1 = escapeTextContentForBrowser; var TEXT_NODE$2 = HTMLNodeType_1.TEXT_NODE; /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function (node, text) { if (text) { var firstChild = node.firstChild; if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE$2) { firstChild.nodeValue = text; return; } } node.textContent = text; }; if (ExecutionEnvironment_1.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function (node, text) { if (node.nodeType === TEXT_NODE$2) { node.nodeValue = text; return; } setInnerHTML_1(node, escapeTextContentForBrowser_1(text)); }; } } var setTextContent_1 = setTextContent; var DOCUMENT_FRAGMENT_NODE = HTMLNodeType_1.DOCUMENT_FRAGMENT_NODE; var ELEMENT_NODE$2 = HTMLNodeType_1.ELEMENT_NODE; /** * In IE (8-11) and Edge, appending nodes with no children is dramatically * faster than appending a full subtree, so we essentially queue up the * .appendChild calls here and apply them so each node is added to its parent * before any children are added. * * In other browsers, doing so is slower or neutral compared to the other order * (in Firefox, twice as slow) so we only do this inversion in IE. * * See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode. */ var enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\bEdge\/\d/.test(navigator.userAgent); function insertTreeChildren(tree) { if (!enableLazy) { return; } var node = tree.node; var children = tree.children; if (children.length) { for (var i = 0; i < children.length; i++) { insertTreeBefore(node, children[i], null); } } else if (tree.html != null) { setInnerHTML_1(node, tree.html); } else if (tree.text != null) { setTextContent_1(node, tree.text); } } var insertTreeBefore = createMicrosoftUnsafeLocalFunction_1(function (parentNode, tree, referenceNode) { // DocumentFragments aren't actually part of the DOM after insertion so // appending children won't update the DOM. We need to ensure the fragment // is properly populated first, breaking out of our lazy approach for just // this level. Also, some <object> plugins (like Flash Player) will read // <param> nodes immediately upon insertion into the DOM, so <object> // must also be populated prior to insertion into the DOM. if (tree.node.nodeType === DOCUMENT_FRAGMENT_NODE || tree.node.nodeType === ELEMENT_NODE$2 && tree.node.nodeName.toLowerCase() === 'object' && (tree.node.namespaceURI == null || tree.node.namespaceURI === DOMNamespaces_1.html)) { insertTreeChildren(tree); parentNode.insertBefore(tree.node, referenceNode); } else { parentNode.insertBefore(tree.node, referenceNode); insertTreeChildren(tree); } }); function replaceChildWithTree(oldNode, newTree) { oldNode.parentNode.replaceChild(newTree.node, oldNode); insertTreeChildren(newTree); } function queueChild(parentTree, childTree) { if (enableLazy) { parentTree.children.push(childTree); } else { parentTree.node.appendChild(childTree.node); } } function queueHTML(tree, html) { if (enableLazy) { tree.html = html; } else { setInnerHTML_1(tree.node, html); } } function queueText(tree, text) { if (enableLazy) { tree.text = text; } else { setTextContent_1(tree.node, text); } } function toString() { return this.node.nodeName; } function DOMLazyTree(node) { return { node: node, children: [], html: null, text: null, toString: toString }; } DOMLazyTree.insertTreeBefore = insertTreeBefore; DOMLazyTree.replaceChildWithTree = replaceChildWithTree; DOMLazyTree.queueChild = queueChild; DOMLazyTree.queueHTML = queueHTML; DOMLazyTree.queueText = queueText; var DOMLazyTree_1 = DOMLazyTree; /** * 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 */ /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browsers builtin objects can report typeof 'function' (e.g. NodeList // in old versions of Safari). !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? invariant_1(false, 'toArray: Array-like object expected') : void 0; !(typeof length === 'number') ? invariant_1(false, 'toArray: Object needs a length property') : void 0; !(length === 0 || length - 1 in obj) ? invariant_1(false, 'toArray: Object should have keys for indices') : void 0; !(typeof obj.callee !== 'function') ? invariant_1(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : void 0; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return ( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } var createArrayFromMixed_1 = createArrayFromMixed; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /*eslint-disable fb-www/unsafe-html */ /** * Dummy container used to detect which wraps are necessary. */ var dummyNode$1 = ExecutionEnvironment_1.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = {}; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap }; // Initialize the SVG elements since we know they'll always need to be wrapped // consistently. If they are created inside a <div> they will be initialized in // the wrong namespace (and will not display). var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; svgElements.forEach(function (nodeName) { markupWrap[nodeName] = svgWrap; shouldWrap[nodeName] = true; }); /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { !!!dummyNode$1 ? invariant_1(false, 'Markup wrapping node not initialized') : void 0; if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode$1.innerHTML = '<link />'; } else { dummyNode$1.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode$1.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } var getMarkupWrap_1 = getMarkupWrap; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /*eslint-disable fb-www/unsafe-html*/ /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment_1.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; !!!dummyNode ? invariant_1(false, 'createNodesFromMarkup dummy not initialized') : void 0; var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap_1(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { !handleScript ? invariant_1(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : void 0; createArrayFromMixed_1(scripts).forEach(handleScript); } var nodes = Array.from(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } var createNodesFromMarkup_1 = createNodesFromMarkup; var Danger = { /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { !ExecutionEnvironment_1.canUseDOM ? invariant_1(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering.') : void 0; !markup ? invariant_1(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : void 0; !(oldChild.nodeName !== 'HTML') ? invariant_1(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString().') : void 0; if (typeof markup === 'string') { var newChild = createNodesFromMarkup_1(markup, emptyFunction_1)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } else { DOMLazyTree_1.replaceChildWithTree(oldChild, markup); } } }; var Danger_1 = Danger; var ReactInvalidSetStateWarningHook = {}; { var processingChildContext = false; var warnInvalidSetState = function () { warning_1(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()'); }; ReactInvalidSetStateWarningHook = { onBeginProcessingChildContext: function () { processingChildContext = true; }, onEndProcessingChildContext: function () { processingChildContext = false; }, onSetState: function () { warnInvalidSetState(); } }; } var ReactInvalidSetStateWarningHook_1 = ReactInvalidSetStateWarningHook; /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactHostOperationHistoryHook * */ // Trust the developer to only use this with a true check var ReactHostOperationHistoryHook = null; { var history = []; ReactHostOperationHistoryHook = { onHostOperation: function (operation) { history.push(operation); }, clearHistory: function () { if (ReactHostOperationHistoryHook._preventClearing) { // Should only be used for tests. return; } history = []; }, getHistory: function () { return history; } }; } var ReactHostOperationHistoryHook_1 = ReactHostOperationHistoryHook; var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; var ReactGlobalSharedState = { ReactCurrentOwner: ReactInternals.ReactCurrentOwner }; { index(ReactGlobalSharedState, { ReactComponentTreeHook: ReactInternals.ReactComponentTreeHook, ReactDebugCurrentFrame: ReactInternals.ReactDebugCurrentFrame }); } var ReactGlobalSharedState_1 = ReactGlobalSharedState; var performance$1; if (ExecutionEnvironment_1.canUseDOM) { performance$1 = window.performance || window.msPerformance || window.webkitPerformance; } var performance_1 = performance$1 || {}; /** * 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 performanceNow; /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (performance_1.now) { performanceNow = function performanceNow() { return performance_1.now(); }; } else { performanceNow = function performanceNow() { return Date.now(); }; } var performanceNow_1 = performanceNow; var ReactComponentTreeHook = ReactGlobalSharedState_1.ReactComponentTreeHook; // Trust the developer to only use this with a true check var ReactDebugTool$1 = null; { var hooks = []; var didHookThrowForEvent = {}; var callHook = function (event, fn, context, arg1, arg2, arg3, arg4, arg5) { try { fn.call(context, arg1, arg2, arg3, arg4, arg5); } catch (e) { warning_1(didHookThrowForEvent[event], 'Exception thrown by hook while handling %s: %s', event, e + '\n' + e.stack); didHookThrowForEvent[event] = true; } }; var emitEvent = function (event, arg1, arg2, arg3, arg4, arg5) { for (var i = 0; i < hooks.length; i++) { var hook = hooks[i]; var fn = hook[event]; if (fn) { callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5); } } }; var isProfiling = false; var flushHistory = []; var lifeCycleTimerStack = []; var currentFlushNesting = 0; var currentFlushMeasurements = []; var currentFlushStartTime = 0; var currentTimerDebugID = null; var currentTimerStartTime = 0; var currentTimerNestedFlushDuration = 0; var currentTimerType = null; var lifeCycleTimerHasWarned = false; var clearHistory = function () { ReactComponentTreeHook.purgeUnmountedComponents(); ReactHostOperationHistoryHook_1.clearHistory(); }; var getTreeSnapshot = function (registeredIDs) { return registeredIDs.reduce(function (tree, id) { var ownerID = ReactComponentTreeHook.getOwnerID(id); var parentID = ReactComponentTreeHook.getParentID(id); tree[id] = { displayName: ReactComponentTreeHook.getDisplayName(id), text: ReactComponentTreeHook.getText(id), updateCount: ReactComponentTreeHook.getUpdateCount(id), childIDs: ReactComponentTreeHook.getChildIDs(id), // Text nodes don't have owners but this is close enough. ownerID: ownerID || parentID && ReactComponentTreeHook.getOwnerID(parentID) || 0, parentID: parentID }; return tree; }, {}); }; var resetMeasurements = function () { var previousStartTime = currentFlushStartTime; var previousMeasurements = currentFlushMeasurements; var previousOperations = ReactHostOperationHistoryHook_1.getHistory(); if (currentFlushNesting === 0) { currentFlushStartTime = 0; currentFlushMeasurements = []; clearHistory(); return; } if (previousMeasurements.length || previousOperations.length) { var registeredIDs = ReactComponentTreeHook.getRegisteredIDs(); flushHistory.push({ duration: performanceNow_1() - previousStartTime, measurements: previousMeasurements || [], operations: previousOperations || [], treeSnapshot: getTreeSnapshot(registeredIDs) }); } clearHistory(); currentFlushStartTime = performanceNow_1(); currentFlushMeasurements = []; }; var checkDebugID = function (debugID) { var allowRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (allowRoot && debugID === 0) { return; } if (!debugID) { warning_1(false, 'ReactDebugTool: debugID may not be empty.'); } }; var beginLifeCycleTimer = function (debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType && !lifeCycleTimerHasWarned) { warning_1(false, 'There is an internal error in the React performance measurement code.' + '\n\nDid not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another'); lifeCycleTimerHasWarned = true; } currentTimerStartTime = performanceNow_1(); currentTimerNestedFlushDuration = 0; currentTimerDebugID = debugID; currentTimerType = timerType; }; var endLifeCycleTimer = function (debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) { warning_1(false, 'There is an internal error in the React performance measurement code. ' + 'We did not expect %s timer to stop while %s timer is still in ' + 'progress for %s instance. Please report this as a bug in React.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another'); lifeCycleTimerHasWarned = true; } if (isProfiling) { currentFlushMeasurements.push({ timerType: timerType, instanceID: debugID, duration: performanceNow_1() - currentTimerStartTime - currentTimerNestedFlushDuration }); } currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; }; var pauseCurrentLifeCycleTimer = function () { var currentTimer = { startTime: currentTimerStartTime, nestedFlushStartTime: performanceNow_1(), debugID: currentTimerDebugID, timerType: currentTimerType }; lifeCycleTimerStack.push(currentTimer); currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; }; var resumeCurrentLifeCycleTimer = function () { var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(), startTime = _lifeCycleTimerStack$.startTime, nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime, debugID = _lifeCycleTimerStack$.debugID, timerType = _lifeCycleTimerStack$.timerType; var nestedFlushDuration = performanceNow_1() - nestedFlushStartTime; currentTimerStartTime = startTime; currentTimerNestedFlushDuration += nestedFlushDuration; currentTimerDebugID = debugID; currentTimerType = timerType; }; var lastMarkTimeStamp = 0; var canUsePerformanceMeasure = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; var shouldMark = function (debugID) { if (!isProfiling || !canUsePerformanceMeasure) { return false; } var element = ReactComponentTreeHook.getElement(debugID); if (element == null || typeof element !== 'object') { return false; } var isHostElement = typeof element.type === 'string'; if (isHostElement) { return false; } return true; }; var markBegin = function (debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; lastMarkTimeStamp = performanceNow_1(); performance.mark(markName); }; var markEnd = function (debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; var displayName = ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown'; // Chrome has an issue of dropping markers recorded too fast: // https://bugs.chromium.org/p/chromium/issues/detail?id=640652 // To work around this, we will not report very small measurements. // I determined the magic number by tweaking it back and forth. // 0.05ms was enough to prevent the issue, but I set it to 0.1ms to be safe. // When the bug is fixed, we can `measure()` unconditionally if we want to. var timeStamp = performanceNow_1(); if (timeStamp - lastMarkTimeStamp > 0.1) { var measurementName = displayName + ' [' + markType + ']'; performance.measure(measurementName, markName); } performance.clearMarks(markName); if (measurementName) { performance.clearMeasures(measurementName); } }; ReactDebugTool$1 = { addHook: function (hook) { hooks.push(hook); }, removeHook: function (hook) { for (var i = 0; i < hooks.length; i++) { if (hooks[i] === hook) { hooks.splice(i, 1); i--; } } }, isProfiling: function () { return isProfiling; }, beginProfiling: function () { if (isProfiling) { return; } isProfiling = true; flushHistory.length = 0; resetMeasurements(); ReactDebugTool$1.addHook(ReactHostOperationHistoryHook_1); }, endProfiling: function () { if (!isProfiling) { return; } isProfiling = false; resetMeasurements(); ReactDebugTool$1.removeHook(ReactHostOperationHistoryHook_1); }, getFlushHistory: function () { return flushHistory; }, onBeginFlush: function () { currentFlushNesting++; resetMeasurements(); pauseCurrentLifeCycleTimer(); emitEvent('onBeginFlush'); }, onEndFlush: function () { resetMeasurements(); currentFlushNesting--; resumeCurrentLifeCycleTimer(); emitEvent('onEndFlush'); }, onBeginLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); emitEvent('onBeginLifeCycleTimer', debugID, timerType); markBegin(debugID, timerType); beginLifeCycleTimer(debugID, timerType); }, onEndLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); endLifeCycleTimer(debugID, timerType); markEnd(debugID, timerType); emitEvent('onEndLifeCycleTimer', debugID, timerType); }, onBeginProcessingChildContext: function () { emitEvent('onBeginProcessingChildContext'); }, onEndProcessingChildContext: function () { emitEvent('onEndProcessingChildContext'); }, onHostOperation: function (operation) { checkDebugID(operation.instanceID); emitEvent('onHostOperation', operation); }, onSetState: function () { emitEvent('onSetState'); }, onSetChildren: function (debugID, childDebugIDs) { checkDebugID(debugID); childDebugIDs.forEach(checkDebugID); emitEvent('onSetChildren', debugID, childDebugIDs); }, onBeforeMountComponent: function (debugID, element, parentDebugID) { checkDebugID(debugID); checkDebugID(parentDebugID, true); emitEvent('onBeforeMountComponent', debugID, element, parentDebugID); markBegin(debugID, 'mount'); }, onMountComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'mount'); emitEvent('onMountComponent', debugID); }, onBeforeUpdateComponent: function (debugID, element) { checkDebugID(debugID); emitEvent('onBeforeUpdateComponent', debugID, element); markBegin(debugID, 'update'); }, onUpdateComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'update'); emitEvent('onUpdateComponent', debugID); }, onBeforeUnmountComponent: function (debugID) { checkDebugID(debugID); emitEvent('onBeforeUnmountComponent', debugID); markBegin(debugID, 'unmount'); }, onUnmountComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'unmount'); emitEvent('onUnmountComponent', debugID); }, onTestEvent: function () { emitEvent('onTestEvent'); } }; ReactDebugTool$1.addHook(ReactInvalidSetStateWarningHook_1); ReactDebugTool$1.addHook(ReactComponentTreeHook); var url = ExecutionEnvironment_1.canUseDOM && window.location.href || ''; if (/[?&]react_perf\b/.test(url)) { ReactDebugTool$1.beginProfiling(); } } var ReactDebugTool_1 = ReactDebugTool$1; // Trust the developer to only use ReactInstrumentation with a true check var debugTool = null; { var ReactDebugTool = ReactDebugTool_1; debugTool = ReactDebugTool; } var ReactInstrumentation = { debugTool: debugTool }; function getNodeAfter(parentNode, node) { // Special case for text components, which return [open, close] comments // from getHostNode. if (Array.isArray(node)) { node = node[1]; } return node ? node.nextSibling : parentNode.firstChild; } /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ var insertChildAt = createMicrosoftUnsafeLocalFunction_1(function (parentNode, childNode, referenceNode) { // We rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. (Using `undefined` is not allowed by all browsers so // we are careful to use `null`.) parentNode.insertBefore(childNode, referenceNode); }); function insertLazyTreeChildAt(parentNode, childTree, referenceNode) { DOMLazyTree_1.insertTreeBefore(parentNode, childTree, referenceNode); } function moveChild(parentNode, childNode, referenceNode) { if (Array.isArray(childNode)) { moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode); } else { insertChildAt(parentNode, childNode, referenceNode); } } function removeChild(parentNode, childNode) { if (Array.isArray(childNode)) { var closingComment = childNode[1]; childNode = childNode[0]; removeDelimitedText(parentNode, childNode, closingComment); parentNode.removeChild(closingComment); } parentNode.removeChild(childNode); } function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) { var node = openingComment; while (true) { var nextNode = node.nextSibling; insertChildAt(parentNode, node, referenceNode); if (node === closingComment) { break; } node = nextNode; } } function removeDelimitedText(parentNode, startNode, closingComment) { while (true) { var node = startNode.nextSibling; if (node === closingComment) { // The closing comment is removed by ReactMultiChild. break; } else { parentNode.removeChild(node); } } } function replaceDelimitedText(openingComment, closingComment, stringText) { var parentNode = openingComment.parentNode; var nodeAfterComment = openingComment.nextSibling; if (nodeAfterComment === closingComment) { // There are no text nodes between the opening and closing comments; insert // a new one if stringText isn't empty. if (stringText) { insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment); } } else { if (stringText) { // Set the text content of the first node after the opening comment, and // remove all following nodes up until the closing comment. setTextContent_1(nodeAfterComment, stringText); removeDelimitedText(parentNode, nodeAfterComment, closingComment); } else { removeDelimitedText(parentNode, openingComment, closingComment); } } { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree_1.getInstanceFromNode(openingComment)._debugID, type: 'replace text', payload: stringText }); } } var dangerouslyReplaceNodeWithMarkup = Danger_1.dangerouslyReplaceNodeWithMarkup; { dangerouslyReplaceNodeWithMarkup = function (oldChild, markup, prevInstance) { Danger_1.dangerouslyReplaceNodeWithMarkup(oldChild, markup); if (prevInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: prevInstance._debugID, type: 'replace with', payload: markup.toString() }); } else { var nextInstance = ReactDOMComponentTree_1.getInstanceFromNode(markup.node); if (nextInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: nextInstance._debugID, type: 'mount', payload: markup.toString() }); } } }; } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup, replaceDelimitedText: replaceDelimitedText, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @internal */ processUpdates: function (parentNode, updates) { { var parentNodeDebugID = ReactDOMComponentTree_1.getInstanceFromNode(parentNode)._debugID; } for (var k = 0; k < updates.length; k++) { var update = updates[k]; switch (update.type) { case 'INSERT_MARKUP': insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode)); { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'insert child', payload: { toIndex: update.toIndex, content: update.content.toString() } }); } break; case 'MOVE_EXISTING': moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode)); { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'move child', payload: { fromIndex: update.fromIndex, toIndex: update.toIndex } }); } break; case 'SET_MARKUP': setInnerHTML_1(parentNode, update.content); { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'replace children', payload: update.content.toString() }); } break; case 'TEXT_CONTENT': setTextContent_1(parentNode, update.content); { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'replace text', payload: update.content.toString() }); } break; case 'REMOVE_NODE': removeChild(parentNode, update.fromNode); { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'remove child', payload: { fromIndex: update.fromIndex } }); } break; } } } }; var DOMChildrenOperations_1 = DOMChildrenOperations; /** * Operations used to process updates to DOM nodes. */ var ReactDOMIDOperations = { /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @internal */ dangerouslyProcessChildrenUpdates: function (parentInst, updates) { var node = ReactDOMComponentTree_1.getNodeFromInstance(parentInst); DOMChildrenOperations_1.processUpdates(node, updates); } }; var ReactDOMIDOperations_1 = ReactDOMIDOperations; /** * Abstracts away all functionality of the reconciler that requires knowledge of * the browser context. TODO: These callers should be refactored to avoid the * need for this injection. */ var ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations_1.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkup: DOMChildrenOperations_1.dangerouslyReplaceNodeWithMarkup }; var ReactComponentBrowserEnvironment_1 = ReactComponentBrowserEnvironment; var AutoFocusUtils = { focusDOMComponent: function () { focusNode_1(ReactDOMComponentTree_1.getNodeFromInstance(this)); } }; var AutoFocusUtils_1 = AutoFocusUtils; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSProperty */ /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridRow: true, gridRowEnd: true, gridRowSpan: true, gridRowStart: true, gridColumn: true, gridColumnEnd: true, gridColumnSpan: true, gridColumnStart: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: true, backgroundColor: true, backgroundImage: true, backgroundPositionX: true, backgroundPositionY: true, backgroundRepeat: true }, backgroundPosition: { backgroundPositionX: true, backgroundPositionY: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true }, outline: { outlineWidth: true, outlineStyle: true, outlineColor: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; var CSSProperty_1 = CSSProperty; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } var camelize_1 = camelize; var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize_1(string.replace(msPattern, 'ms-')); } var camelizeStyleName_1 = camelizeStyleName; var isUnitlessNumber$1 = CSSProperty_1.isUnitlessNumber; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @param {ReactDOMComponent} component * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, component) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } if (typeof value === 'number' && value !== 0 && !(isUnitlessNumber$1.hasOwnProperty(name) && isUnitlessNumber$1[name])) { return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers } return ('' + value).trim(); } var dangerousStyleValue_1 = dangerousStyleValue; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getComponentName * */ function getComponentName(instanceOrFiber) { if (typeof instanceOrFiber.getName === 'function') { // Stack reconciler var instance = instanceOrFiber; return instance.getName(); } if (typeof instanceOrFiber.tag === 'number') { // Fiber reconciler var fiber = instanceOrFiber; var type = fiber.type; if (typeof type === 'string') { return type; } if (typeof type === 'function') { return type.displayName || type.name; } } return null; } var getComponentName_1 = getComponentName; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } var hyphenate_1 = hyphenate; var msPattern$1 = /^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_1(string).replace(msPattern$1, '-ms-'); } var hyphenateStyleName_1 = hyphenateStyleName; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * * @typechecks static-only */ /** * Memoizes the return value of a function that accepts one string argument. */ function memoizeStringOnly(callback) { var cache = {}; return function (string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } var memoizeStringOnly_1 = memoizeStringOnly; var IndeterminateComponent = ReactTypeOfWork.IndeterminateComponent; var FunctionalComponent = ReactTypeOfWork.FunctionalComponent; var ClassComponent = ReactTypeOfWork.ClassComponent; var HostComponent$2 = ReactTypeOfWork.HostComponent; function describeComponentFrame(name, source, ownerName) { return '\n in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : ''); } function describeFiber(fiber) { switch (fiber.tag) { case IndeterminateComponent: case FunctionalComponent: case ClassComponent: case HostComponent$2: var owner = fiber._debugOwner; var source = fiber._debugSource; var name = getComponentName_1(fiber); var ownerName = null; if (owner) { ownerName = getComponentName_1(owner); } return describeComponentFrame(name, source, ownerName); default: return ''; } } // This function can only be called with a work-in-progress fiber and // only during begin or complete phase. Do not call it under any other // circumstances. function getStackAddendumByWorkInProgressFiber$1(workInProgress) { var info = ''; var node = workInProgress; do { info += describeFiber(node); // Otherwise this return pointer might point to the wrong tree: node = node['return']; } while (node); return info; } var ReactFiberComponentTreeHook = { getStackAddendumByWorkInProgressFiber: getStackAddendumByWorkInProgressFiber$1, describeComponentFrame: describeComponentFrame }; { var getComponentName$1 = getComponentName_1; var _require$3 = ReactFiberComponentTreeHook, getStackAddendumByWorkInProgressFiber = _require$3.getStackAddendumByWorkInProgressFiber; } function getCurrentFiberOwnerName$1() { { var fiber = ReactDebugCurrentFiber.current; if (fiber === null) { return null; } if (fiber._debugOwner != null) { return getComponentName$1(fiber._debugOwner); } } return null; } function getCurrentFiberStackAddendum() { { var fiber = ReactDebugCurrentFiber.current; if (fiber === null) { return null; } // Safe because if current fiber exists, we are reconciling, // and it is guaranteed to be the work-in-progress version. return getStackAddendumByWorkInProgressFiber(fiber); } return null; } var ReactDebugCurrentFiber = { current: null, phase: null, getCurrentFiberOwnerName: getCurrentFiberOwnerName$1, getCurrentFiberStackAddendum: getCurrentFiberStackAddendum }; var ReactDebugCurrentFiber_1 = ReactDebugCurrentFiber; { var _require$2 = ReactDebugCurrentFiber_1, getCurrentFiberOwnerName = _require$2.getCurrentFiberOwnerName; } var processStyleName = memoizeStringOnly_1(function (styleName) { return hyphenateStyleName_1(styleName); }); var hasShorthandPropertyBug = false; if (ExecutionEnvironment_1.canUseDOM) { var tempStyle = document.createElement('div').style; try { // IE8 throws "Invalid argument." if resetting shorthand style properties. tempStyle.font = ''; } catch (e) { hasShorthandPropertyBug = true; } } { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnedForNaNValue = false; var warnedForInfinityValue = false; var warnHyphenatedStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; warning_1(false, 'Unsupported style property %s. Did you mean %s?%s', name, camelizeStyleName_1(name), checkRenderMessage(owner)); }; var warnBadVendoredStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; warning_1(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?%s', name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)); }; var warnStyleValueWithSemicolon = function (name, value, owner) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; warning_1(false, "Style property values shouldn't contain a semicolon.%s " + 'Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, '')); }; var warnStyleValueIsNaN = function (name, value, owner) { if (warnedForNaNValue) { return; } warnedForNaNValue = true; warning_1(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)); }; var warnStyleValueIsInfinity = function (name, value, owner) { if (warnedForInfinityValue) { return; } warnedForInfinityValue = true; warning_1(false, '`Infinity` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)); }; var checkRenderMessage = function (owner) { var ownerName; if (owner != null) { // Stack passes the owner manually all the way to CSSPropertyOperations. ownerName = getComponentName_1(owner); } else { // Fiber doesn't pass it but uses ReactDebugCurrentFiber to track it. // It is only enabled in development and tracks host components too. ownerName = getCurrentFiberOwnerName(); // TODO: also report the stack. } if (ownerName) { return '\n\nCheck the render method of `' + ownerName + '`.'; } return ''; }; /** * @param {string} name * @param {*} value * @param {ReactDOMComponent} component */ var warnValidStyle = function (name, value, component) { // Don't warn for CSS variables if (name.indexOf('--') === 0) { return; } var owner; if (component) { owner = component._currentElement._owner; } if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name, owner); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name, owner); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value, owner); } if (typeof value === 'number') { if (isNaN(value)) { warnStyleValueIsNaN(name, value, owner); } else if (!isFinite(value)) { warnStyleValueIsInfinity(name, value, owner); } } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @param {ReactDOMComponent} component * @return {?string} */ createMarkupForStyles: function (styles, component) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; { warnValidStyle(styleName, styleValue, component); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue_1(styleName, styleValue, component) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles * @param {ReactDOMComponent} component */ setValueForStyles: function (node, styles, component) { var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } { warnValidStyle(styleName, styles[styleName], component); } var styleValue = dangerousStyleValue_1(styleName, styles[styleName], component); if (styleName === 'float') { styleName = 'cssFloat'; } if (styleName.indexOf('--') === 0) { style.setProperty(styleName, styleValue); } else if (styleValue) { style[styleName] = styleValue; } else { var expansion = hasShorthandPropertyBug && CSSProperty_1.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; var CSSPropertyOperations_1 = CSSPropertyOperations; /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser_1(value) + '"'; } var quoteAttributeValueForBrowser_1 = quoteAttributeValueForBrowser; var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty_1.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty_1.ATTRIBUTE_NAME_CHAR + ']*$'); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { return true; } if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; warning_1(false, 'Invalid attribute name: `%s`', attributeName); return false; } function shouldIgnoreValue(propertyInfo, value) { return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function (id) { return DOMProperty_1.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser_1(id); }, setAttributeForID: function (node, id) { node.setAttribute(DOMProperty_1.ID_ATTRIBUTE_NAME, id); }, createMarkupForRoot: function () { return DOMProperty_1.ROOT_ATTRIBUTE_NAME + '=""'; }, setAttributeForRoot: function (node) { node.setAttribute(DOMProperty_1.ROOT_ATTRIBUTE_NAME, ''); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function (name, value) { var propertyInfo = DOMProperty_1.properties.hasOwnProperty(name) ? DOMProperty_1.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) { return ''; } var attributeName = propertyInfo.attributeName; if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { return attributeName + '=""'; } return attributeName + '=' + quoteAttributeValueForBrowser_1(value); } else if (DOMProperty_1.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser_1(value); } return null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function (name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser_1(value); }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function (node, name, value) { var propertyInfo = DOMProperty_1.properties.hasOwnProperty(name) ? DOMProperty_1.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(propertyInfo, value)) { DOMPropertyOperations.deleteValueForProperty(node, name); return; } else if (propertyInfo.mustUseProperty) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propertyInfo.propertyName] = value; } else { var attributeName = propertyInfo.attributeName; var namespace = propertyInfo.attributeNamespace; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. if (namespace) { node.setAttributeNS(namespace, attributeName, '' + value); } else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { node.setAttribute(attributeName, ''); } else { node.setAttribute(attributeName, '' + value); } } } else if (DOMProperty_1.isCustomAttribute(name)) { DOMPropertyOperations.setValueForAttribute(node, name, value); return; } { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree_1.getInstanceFromNode(node)._debugID, type: 'update attribute', payload: payload }); } }, setValueForAttribute: function (node, name, value) { if (!isAttributeNameSafe(name)) { return; } if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree_1.getInstanceFromNode(node)._debugID, type: 'update attribute', payload: payload }); } }, /** * Deletes an attributes from a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForAttribute: function (node, name) { node.removeAttribute(name); { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree_1.getInstanceFromNode(node)._debugID, type: 'remove attribute', payload: name }); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function (node, name) { var propertyInfo = DOMProperty_1.properties.hasOwnProperty(name) ? DOMProperty_1.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, undefined); } else if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; if (propertyInfo.hasBooleanValue) { node[propName] = false; } else { node[propName] = ''; } } else { node.removeAttribute(propertyInfo.attributeName); } } else if (DOMProperty_1.isCustomAttribute(name)) { node.removeAttribute(name); } { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree_1.getInstanceFromNode(node)._debugID, type: 'remove attribute', payload: name }); } } }; var DOMPropertyOperations_1 = DOMPropertyOperations; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret; { var invariant$2 = invariant_1; var warning$2 = warning_1; var ReactPropTypesSecret$1 = ReactPropTypesSecret_1; var loggedTypeFailures$1 = {}; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. invariant$2(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1); } catch (ex) { error = ex; } warning$2(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error); if (error instanceof Error && !(error.message in loggedTypeFailures$1)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures$1[error.message] = true; var stack = getStack ? getStack() : ''; warning$2(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } } var checkPropTypes_1 = checkPropTypes; var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret_1) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package invariant_1( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); } else if ('development' !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { warning_1( false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction_1.thatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { warning_1(false, 'Invalid argument supplied to oneOf, expected an instance of array.'); return emptyFunction_1.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { warning_1(false, 'Invalid argument supplied to oneOfType, expected an instance of array.'); return emptyFunction_1.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes_1; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; var index$2 = createCommonjsModule(function (module) { /** * 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. */ { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = factoryWithTypeCheckers(isValidElement, throwOnDirectAccess); } }); /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * * @providesModule ReactPropTypesSecret */ var ReactPropTypesSecret$2 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1$2 = ReactPropTypesSecret$2; var hasReadOnlyValue = { button: true, checkbox: true, image: true, hidden: true, radio: true, reset: true, submit: true }; var propTypes = { value: function (props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, checked: function (props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, onChange: index$2.func }; var loggedTypeFailures = {}; /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var ReactControlledValuePropTypes = { checkPropTypes: function (tagName, props, getStack) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, tagName, 'prop', null, ReactPropTypesSecret_1$2); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; warning_1(false, 'Failed form propType: %s%s', error.message, getStack()); } } } }; var ReactControlledValuePropTypes_1 = ReactControlledValuePropTypes; { var getStackAddendumByID = ReactGlobalSharedState_1.ReactComponentTreeHook.getStackAddendumByID; } var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function isControlled(props) { var usesChecked = props.type === 'checkbox' || props.type === 'radio'; return usesChecked ? props.checked != null : props.value != null; } /** * Implements an <input> host component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = { getHostProps: function (inst, props) { var value = props.value; var checked = props.checked; var hostProps = index({ // Make sure we set .type before any other properties (setting .value // before .type means .value is lost in IE11 and below) type: undefined, // Make sure we set .step before .value (setting .value before .step // means .value is rounded on mount, based upon step precision) step: undefined, // Make sure we set .min & .max before .value (to ensure proper order // in corner cases such as min or max deriving from value, e.g. Issue #7170) min: undefined, max: undefined }, props, { defaultChecked: undefined, defaultValue: undefined, value: value != null ? value : inst._wrapperState.initialValue, checked: checked != null ? checked : inst._wrapperState.initialChecked }); return hostProps; }, mountWrapper: function (inst, props) { { var owner = inst._currentElement._owner; ReactControlledValuePropTypes_1.checkPropTypes('input', props, function () { return getStackAddendumByID(inst._debugID); }); if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { warning_1(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type); didWarnCheckedDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { warning_1(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type); didWarnValueDefaultValue = true; } } var defaultValue = props.defaultValue; inst._wrapperState = { initialChecked: props.checked != null ? props.checked : props.defaultChecked, initialValue: props.value != null ? props.value : defaultValue, listeners: null, controlled: isControlled(props) }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; { var controlled = isControlled(props); if (!inst._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { warning_1(false, 'A component is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s', props.type, getStackAddendumByID(inst._debugID)); didWarnUncontrolledToControlled = true; } if (inst._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { warning_1(false, 'A component is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s', props.type, getStackAddendumByID(inst._debugID)); didWarnControlledToUncontrolled = true; } } var checked = props.checked; if (checked != null) { DOMPropertyOperations_1.setValueForProperty(ReactDOMComponentTree_1.getNodeFromInstance(inst), 'checked', checked || false); } var node = ReactDOMComponentTree_1.getNodeFromInstance(inst); var value = props.value; if (value != null) { if (value === 0 && node.value === '') { node.value = '0'; // Note: IE9 reports a number inputs as 'text', so check props instead. } else if (props.type === 'number') { // Simulate `input.valueAsNumber`. IE9 does not support it var valueAsNumber = parseFloat(node.value, 10) || 0; // eslint-disable-next-line if (value != valueAsNumber) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. node.value = '' + value; } // eslint-disable-next-line } else if (value != node.value) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. node.value = '' + value; } } else { if (props.value == null && props.defaultValue != null) { // In Chrome, assigning defaultValue to certain input types triggers input validation. // For number inputs, the display value loses trailing decimal points. For email inputs, // Chrome raises "The specified value <x> is not a valid email address". // // Here we check to see if the defaultValue has actually changed, avoiding these problems // when the user is inputting text // // https://github.com/facebook/react/issues/7253 if (node.defaultValue !== '' + props.defaultValue) { node.defaultValue = '' + props.defaultValue; } } if (props.checked == null && props.defaultChecked != null) { node.defaultChecked = !!props.defaultChecked; } } }, postMountWrapper: function (inst) { var props = inst._currentElement.props; // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var node = ReactDOMComponentTree_1.getNodeFromInstance(inst); // Detach value from defaultValue. We won't do anything if we're working on // submit or reset inputs as those values & defaultValues are linked. They // are not resetable nodes so this operation doesn't matter and actually // removes browser-default values (eg "Submit Query") when no value is // provided. switch (props.type) { case 'submit': case 'reset': break; case 'color': case 'date': case 'datetime': case 'datetime-local': case 'month': case 'time': case 'week': // This fixes the no-show issue on iOS Safari and Android Chrome: // https://github.com/facebook/react/issues/7233 node.value = ''; node.value = node.defaultValue; break; default: node.value = node.value; break; } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug // this is needed to work around a chrome bug where setting defaultChecked // will sometimes influence the value of checked (even after detachment). // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 // We need to temporarily unset name to avoid disrupting radio button groups. var name = node.name; if (name !== '') { node.name = ''; } node.defaultChecked = !node.defaultChecked; node.defaultChecked = !node.defaultChecked; if (name !== '') { node.name = name; } }, restoreControlledState: function (inst) { if (inst._rootNodeID) { // DOM component is still mounted; update ReactDOMInput.updateWrapper(inst); } var props = inst._currentElement.props; updateNamedCousins(inst, props); } }; function updateNamedCousins(thisInstance, props) { var name = props.name; if (props.type === 'radio' && name != null) { var rootNode = ReactDOMComponentTree_1.getNodeFromInstance(thisInstance); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form. It might not even be in the // document. Let's just use the local `querySelectorAll` to ensure we don't // miss anything. var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React radio buttons with non-React ones. var otherInstance = ReactDOMComponentTree_1.getInstanceFromNode(otherNode); !otherInstance ? invariant_1(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : void 0; // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. if (otherInstance._rootNodeID) { ReactDOMInput.updateWrapper(otherInstance); } } } } var ReactDOMInput_1 = ReactDOMInput; { var getStackAddendumByID$1 = ReactGlobalSharedState_1.ReactComponentTreeHook.getStackAddendumByID; } var didWarnValueDefaultValue$1 = false; function getDeclarationErrorAddendum$1(owner) { if (owner) { var name = owner.getName(); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. * @private */ function checkSelectPropTypes(inst, props) { var owner = inst._currentElement._owner; ReactControlledValuePropTypes_1.checkPropTypes('select', props, function () { return getStackAddendumByID$1(inst._debugID); }); for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } var isArray = Array.isArray(props[propName]); if (props.multiple && !isArray) { warning_1(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum$1(owner)); } else if (!props.multiple && isArray) { warning_1(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum$1(owner)); } } } /** * @param {ReactDOMComponent} inst * @param {boolean} multiple * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(inst, multiple, propValue) { var options = ReactDOMComponentTree_1.getNodeFromInstance(inst).options; if (multiple) { var selectedValue = {}; for (var i = 0; i < propValue.length; i++) { selectedValue['' + propValue[i]] = true; } for (var _i = 0; _i < options.length; _i++) { var selected = selectedValue.hasOwnProperty(options[_i].value); if (options[_i].selected !== selected) { options[_i].selected = selected; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. var _selectedValue = '' + propValue; for (var _i2 = 0; _i2 < options.length; _i2++) { if (options[_i2].value === _selectedValue) { options[_i2].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> host component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = { getHostProps: function (inst, props) { return index({}, props, { value: undefined }); }, mountWrapper: function (inst, props) { { checkSelectPropTypes(inst, props); } var value = props.value; inst._wrapperState = { initialValue: value != null ? value : props.defaultValue, listeners: null, wasMultiple: !!props.multiple }; if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) { warning_1(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components'); didWarnValueDefaultValue$1 = true; } }, getSelectValueContext: function (inst) { // ReactDOMOption looks at this initial value so the initial generated // markup has correct `selected` attributes return inst._wrapperState.initialValue; }, postUpdateWrapper: function (inst) { var props = inst._currentElement.props; // After the initial mount, we control selected-ness manually so don't pass // this value down inst._wrapperState.initialValue = undefined; var wasMultiple = inst._wrapperState.wasMultiple; inst._wrapperState.wasMultiple = !!props.multiple; var value = props.value; if (value != null) { updateOptions(inst, !!props.multiple, value); } else if (wasMultiple !== !!props.multiple) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(inst, !!props.multiple, props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(inst, !!props.multiple, props.multiple ? [] : ''); } } }, restoreControlledState: function (inst) { if (inst._rootNodeID) { var props = inst._currentElement.props; var value = props.value; if (value != null) { updateOptions(inst, !!props.multiple, value); } } } }; var ReactDOMSelect_1 = ReactDOMSelect; var didWarnInvalidOptionChildren = false; function flattenChildren(children) { var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. React.Children.forEach(children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else if (!didWarnInvalidOptionChildren) { didWarnInvalidOptionChildren = true; warning_1(false, 'Only strings and numbers are supported as <option> children.'); } }); return content; } /** * Implements an <option> host component that warns when `selected` is set. */ var ReactDOMOption = { mountWrapper: function (inst, props, hostParent) { // TODO (yungsters): Remove support for `selected` in <option>. { warning_1(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.'); } // Look up whether this option is 'selected' var selectValue = null; if (hostParent != null) { var selectParent = hostParent; if (selectParent._tag === 'optgroup') { selectParent = selectParent._hostParent; } if (selectParent != null && selectParent._tag === 'select') { selectValue = ReactDOMSelect_1.getSelectValueContext(selectParent); } } // If the value is null (e.g., no specified value or after initial mount) // or missing (e.g., for <datalist>), we don't change props.selected var selected = null; if (selectValue != null) { var value; if (props.value != null) { value = props.value + ''; } else { value = flattenChildren(props.children); } selected = false; if (Array.isArray(selectValue)) { // multiple for (var i = 0; i < selectValue.length; i++) { if ('' + selectValue[i] === value) { selected = true; break; } } } else { selected = '' + selectValue === value; } } inst._wrapperState = { selected: selected }; }, postMountWrapper: function (inst) { // value="" should make a value attribute (#6219) var props = inst._currentElement.props; if (props.value != null) { var node = ReactDOMComponentTree_1.getNodeFromInstance(inst); node.setAttribute('value', props.value); } }, getHostProps: function (inst, props) { var hostProps = index({ selected: undefined, children: undefined }, props); // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering if (inst._wrapperState.selected != null) { hostProps.selected = inst._wrapperState.selected; } var content = flattenChildren(props.children); if (content) { hostProps.children = content; } return hostProps; } }; var ReactDOMOption_1 = ReactDOMOption; { var getStackAddendumByID$2 = ReactGlobalSharedState_1.ReactComponentTreeHook.getStackAddendumByID; } var didWarnValDefaultVal = false; /** * Implements a <textarea> host component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = { getHostProps: function (inst, props) { !(props.dangerouslySetInnerHTML == null) ? invariant_1(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : void 0; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. We could add a check in setTextContent // to only set the value if/when the value differs from the node value (which would // completely solve this IE9 bug), but Sebastian+Ben seemed to like this solution. // The value can be a boolean or object so that's why it's forced to be a string. var hostProps = index({}, props, { value: undefined, defaultValue: undefined, children: '' + inst._wrapperState.initialValue }); return hostProps; }, mountWrapper: function (inst, props) { { ReactControlledValuePropTypes_1.checkPropTypes('textarea', props, function () { return getStackAddendumByID$2(inst._debugID); }); if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) { warning_1(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components'); didWarnValDefaultVal = true; } } var value = props.value; var initialValue = value; // Only bother fetching default value if we're going to use it if (value == null) { var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = props.children; if (children != null) { { warning_1(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.'); } !(defaultValue == null) ? invariant_1(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : void 0; if (Array.isArray(children)) { !(children.length <= 1) ? invariant_1(false, '<textarea> can only have at most one child.') : void 0; children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } inst._wrapperState = { initialValue: '' + initialValue, listeners: null }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; var node = ReactDOMComponentTree_1.getNodeFromInstance(inst); var value = props.value; if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. var newValue = '' + value; // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } if (props.defaultValue == null) { node.defaultValue = newValue; } } if (props.defaultValue != null) { node.defaultValue = props.defaultValue; } }, postMountWrapper: function (inst) { // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var node = ReactDOMComponentTree_1.getNodeFromInstance(inst); var textContent = node.textContent; // Only set node.value if textContent is equal to the expected // initial value. In IE10/IE11 there is a bug where the placeholder attribute // will populate textContent as well. // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/ if (textContent === inst._wrapperState.initialValue) { node.value = textContent; } }, restoreControlledState: function (inst) { if (inst._rootNodeID) { // DOM component is still mounted; update ReactDOMTextarea.updateWrapper(inst); } } }; var ReactDOMTextarea_1 = ReactDOMTextarea; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceMap */ /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function (key) { key._reactInternalInstance = undefined; }, get: function (key) { return key._reactInternalInstance; }, has: function (key) { return key._reactInternalInstance !== undefined; }, set: function (key, value) { key._reactInternalInstance = value; } }; var ReactInstanceMap_1 = ReactInstanceMap; /** * 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. * */ var emptyObject = {}; { Object.freeze(emptyObject); } var emptyObject_1 = emptyObject; var ClassComponent$1 = ReactTypeOfWork.ClassComponent; /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ function isValidOwner(object) { return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); } /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function (component, ref, owner) { if (owner && owner.tag === ClassComponent$1) { var inst = owner.stateNode; var refs = inst.refs === emptyObject_1 ? inst.refs = {} : inst.refs; refs[ref] = component.getPublicInstance(); } else { !isValidOwner(owner) ? invariant_1(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : void 0; owner.attachRef(ref, component); } }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function (component, ref, owner) { if (owner && owner.tag === ClassComponent$1) { var inst = owner.stateNode; if (inst && inst.refs[ref] === component.getPublicInstance()) { delete inst.refs[ref]; } } else { !isValidOwner(owner) ? invariant_1(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : void 0; var ownerPublicInstance = owner.getPublicInstance(); // Check that `component`'s owner is still alive and that `component` is still the current ref // because we do not want to detach the ref if another component stole it. if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } } }; var ReactOwner_1 = ReactOwner; var ReactCompositeComponentTypes$1 = { ImpureClass: 0, PureClass: 1, StatelessFunctional: 2 }; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCompositeComponentTypes * */ var ReactRef = {}; { var ReactCompositeComponentTypes = ReactCompositeComponentTypes$1; var _require$4 = ReactGlobalSharedState_1, ReactComponentTreeHook$1 = _require$4.ReactComponentTreeHook; var warning$3 = warning_1; var warnedAboutStatelessRefs = {}; } function attachRef(ref, component, owner) { { if (component._compositeType === ReactCompositeComponentTypes.StatelessFunctional) { var info = ''; var ownerName = void 0; if (owner) { if (typeof owner.getName === 'function') { ownerName = owner.getName(); } if (ownerName) { info += '\n\nCheck the render method of `' + ownerName + '`.'; } } var warningKey = ownerName || component._debugID; var element = component._currentElement; if (element && element._source) { warningKey = element._source.fileName + ':' + element._source.lineNumber; } if (!warnedAboutStatelessRefs[warningKey]) { warnedAboutStatelessRefs[warningKey] = true; warning$3(false, 'Stateless function components cannot be given refs. ' + 'Attempts to access this ref will fail.%s%s', info, ReactComponentTreeHook$1.getStackAddendumByID(component._debugID)); } } } if (typeof ref === 'function') { ref(component.getPublicInstance()); } else { // Legacy ref ReactOwner_1.addComponentAsRefTo(component, ref, owner); } } function detachRef(ref, component, owner) { if (typeof ref === 'function') { ref(null); } else { // Legacy ref ReactOwner_1.removeComponentAsRefFrom(component, ref, owner); } } ReactRef.attachRefs = function (instance, element) { if (element === null || typeof element !== 'object') { return; } var ref = element.ref; if (ref != null) { attachRef(ref, instance, element._owner); } }; ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. var prevRef = null; var prevOwner = null; if (prevElement !== null && typeof prevElement === 'object') { prevRef = prevElement.ref; prevOwner = prevElement._owner; } var nextRef = null; var nextOwner = null; if (nextElement !== null && typeof nextElement === 'object') { nextRef = nextElement.ref; nextOwner = nextElement._owner; } return prevRef !== nextRef || // If owner changes but we have an unchanged function ref, don't update refs typeof nextRef === 'string' && nextOwner !== prevOwner; }; ReactRef.detachRefs = function (instance, element) { if (element === null || typeof element !== 'object') { return; } var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; var ReactRef_1 = ReactRef; /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef_1.attachRefs(this, this._currentElement); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} the containing host component instance * @param {?object} info about the host container * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID) // 0 in production and for roots { { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement, parentDebugID); } } var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context, parentDebugID); if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID); } } return markup; }, /** * Returns a value that can be passed to * ReactComponentEnvironment.replaceNodeWithMarkup. */ getHostNode: function (internalInstance) { return internalInstance.getHostNode(); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (internalInstance, safely, skipLifecycle) { { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID); } } ReactRef_1.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(safely, skipLifecycle); { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID); } } }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function (internalInstance, nextElement, transaction, context) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && context === internalInstance._context) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for an element created outside a composite to be // deeply mutated and reused. // TODO: Bailing out early is just a perf optimization right? // TODO: Removing the return statement should affect correctness? return; } { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement); } } var refsChanged = ReactRef_1.shouldUpdateRefs(prevElement, nextElement); if (refsChanged) { ReactRef_1.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (internalInstance, transaction, updateBatchNumber) { if (internalInstance._updateBatchNumber !== updateBatchNumber) { // The component's enqueued batch number should always be the current // batch or the following one. warning_1(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber); return; } { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement); } } internalInstance.performUpdateIfNecessary(transaction); { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } } }; var ReactReconciler_1 = ReactReconciler; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule KeyEscapeUtils * */ /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; var KeyEscapeUtils_1 = KeyEscapeUtils; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactFeatureFlags * */ var ReactFeatureFlags = { // When true, call console.time() before and .timeEnd() after each top-level // render (both initial renders and updates). Useful when looking at prod-mode // timeline profiles in Chrome, for example. logTopLevelRenders: false, prepareNewChildrenBeforeUnmountInStack: true, disableNewFiberFeatures: false, enableAsyncSubtreeAPI: false }; var ReactFeatureFlags_1 = ReactFeatureFlags; var ReactNodeTypes = { HOST: 0, COMPOSITE: 1, EMPTY: 2, getType: function (node) { if (node === null || node === false) { return ReactNodeTypes.EMPTY; } else if (React.isValidElement(node)) { if (typeof node.type === 'function') { return ReactNodeTypes.COMPOSITE; } else { return ReactNodeTypes.HOST; } } invariant_1(false, 'Unexpected node: %s', node); } }; var ReactNodeTypes_1 = ReactNodeTypes; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shouldUpdateReactComponent */ /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; if (prevEmpty || nextEmpty) { return prevEmpty === nextEmpty; } var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return nextType === 'string' || nextType === 'number'; } else { return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } } var shouldUpdateReactComponent_1 = shouldUpdateReactComponent; var ReactCurrentOwner$1 = ReactGlobalSharedState_1.ReactCurrentOwner; { var _require2$1 = ReactGlobalSharedState_1, ReactDebugCurrentFrame = _require2$1.ReactDebugCurrentFrame; var warningAboutMissingGetChildContext = {}; } function StatelessComponent(Component) {} StatelessComponent.prototype.render = function () { var Component = ReactInstanceMap_1.get(this)._currentElement.type; var element = Component(this.props, this.context, this.updater); return element; }; function shouldConstruct(Component) { return !!(Component.prototype && Component.prototype.isReactComponent); } function isPureComponent(Component) { return !!(Component.prototype && Component.prototype.isPureReactComponent); } // Separated into a function to contain deoptimizations caused by try/finally. function measureLifeCyclePerf(fn, debugID, timerType) { if (debugID === 0) { // Top-level wrappers (see ReactMount) and empty components (see // ReactDOMEmptyComponent) are invisible to hooks and devtools. // Both are implementation details that should go away in the future. return fn(); } ReactInstrumentation.debugTool.onBeginLifeCycleTimer(debugID, timerType); try { return fn(); } finally { ReactInstrumentation.debugTool.onEndLifeCycleTimer(debugID, timerType); } } /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponent = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function (element) { this._currentElement = element; this._rootNodeID = 0; this._compositeType = null; this._instance = null; this._hostParent = null; this._hostContainerInfo = null; // See ReactUpdateQueue this._updateBatchNumber = null; this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedNodeType = null; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._topLevelWrapper = null; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; // ComponentWillUnmount shall only be called once this._calledComponentWillUnmount = false; { this._warnedAboutRefsInRender = false; } }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} hostParent * @param {?object} hostContainerInfo * @param {?object} context * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { var _this = this; this._context = context; this._mountOrder = nextMountID++; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var publicProps = this._currentElement.props; var publicContext = this._processContext(context); var Component = this._currentElement.type; var updateQueue = transaction.getUpdateQueue(); // Initialize the public class var doConstruct = shouldConstruct(Component); var inst = this._constructComponent(doConstruct, publicProps, publicContext, updateQueue); var renderedElement; // Support functional components if (!doConstruct && (inst == null || inst.render == null)) { renderedElement = inst; { warning_1(!Component.childContextTypes, '%s(...): childContextTypes cannot be defined on a functional component.', Component.displayName || Component.name || 'Component'); } !(inst === null || inst === false || React.isValidElement(inst)) ? invariant_1(false, '%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : void 0; inst = new StatelessComponent(Component); this._compositeType = ReactCompositeComponentTypes$1.StatelessFunctional; } else { if (isPureComponent(Component)) { this._compositeType = ReactCompositeComponentTypes$1.PureClass; } else { this._compositeType = ReactCompositeComponentTypes$1.ImpureClass; } } { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging if (inst.render == null) { warning_1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', Component.displayName || Component.name || 'Component'); } var propsMutated = inst.props !== publicProps; var componentName = Component.displayName || Component.name || 'Component'; warning_1(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", componentName, componentName); } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps; inst.context = publicContext; inst.refs = emptyObject_1; inst.updater = updateQueue; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap_1.set(inst, this); { // Since plain JS classes are defined without any special initialization // logic, we can not catch common errors early. Therefore, we have to // catch them here, at initialization time, instead. warning_1(!inst.getInitialState || inst.getInitialState.isReactClassApproved || inst.state, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component'); warning_1(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component'); warning_1(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component'); warning_1(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component'); warning_1(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component'); warning_1(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component'); warning_1(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component'); if (isPureComponent(Component) && typeof inst.shouldComponentUpdate !== 'undefined') { warning_1(false, '%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', this.getName() || 'A pure component'); } warning_1(!inst.defaultProps, 'defaultProps was defined as an instance property on %s. Use a static ' + 'property to define defaultProps instead.', this.getName() || 'a component'); } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? invariant_1(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : void 0; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; if (inst.componentWillMount) { { measureLifeCyclePerf(function () { return inst.componentWillMount(); }, this._debugID, 'componentWillMount'); } // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. if (this._pendingStateQueue) { inst.state = this._processPendingState(inst.props, inst.context); } } var markup; if (inst.unstable_handleError) { markup = this.performInitialMountWithErrorHandling(renderedElement, hostParent, hostContainerInfo, transaction, context); } else { markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } if (inst.componentDidMount) { { transaction.getReactMountReady().enqueue(function () { measureLifeCyclePerf(function () { return inst.componentDidMount(); }, _this._debugID, 'componentDidMount'); }); } } // setState callbacks during willMount should end up here var callbacks = this._pendingCallbacks; if (callbacks) { this._pendingCallbacks = null; for (var i = 0; i < callbacks.length; i++) { transaction.getReactMountReady().enqueue(callbacks[i], inst); } } return markup; }, _constructComponent: function (doConstruct, publicProps, publicContext, updateQueue) { { ReactCurrentOwner$1.current = this; try { return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); } finally { ReactCurrentOwner$1.current = null; } } }, _constructComponentWithoutOwner: function (doConstruct, publicProps, publicContext, updateQueue) { var Component = this._currentElement.type; if (doConstruct) { { return measureLifeCyclePerf(function () { return new Component(publicProps, publicContext, updateQueue); }, this._debugID, 'ctor'); } } // This can still be an instance in case of factory components // but we'll count this as time spent rendering as the more common case. { return measureLifeCyclePerf(function () { return Component(publicProps, publicContext, updateQueue); }, this._debugID, 'render'); } }, performInitialMountWithErrorHandling: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { var markup; var checkpoint = transaction.checkpoint(); try { markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } catch (e) { // Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint transaction.rollback(checkpoint); this._instance.unstable_handleError(e); if (this._pendingStateQueue) { this._instance.state = this._processPendingState(this._instance.props, this._instance.context); } checkpoint = transaction.checkpoint(); this._renderedComponent.unmountComponent(true /* safely */ , // Don't call componentWillUnmount() because they never fully mounted: true /* skipLifecyle */ ); transaction.rollback(checkpoint); // Try again - we've informed the component about the error, so they can render an error message this time. // If this throws again, the error will bubble up (and can be caught by a higher error boundary). markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } return markup; }, performInitialMount: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { // If not a stateless component, we now render if (renderedElement === undefined) { renderedElement = this._renderValidatedComponent(); } var nodeType = ReactNodeTypes_1.getType(renderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes_1.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var debugID = 0; { debugID = this._debugID; } var markup = ReactReconciler_1.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context), debugID); { if (debugID !== 0) { var childDebugIDs = child._debugID !== 0 ? [child._debugID] : []; ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs); } } return markup; }, getHostNode: function () { return ReactReconciler_1.getHostNode(this._renderedComponent); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (safely, skipLifecycle) { if (!this._renderedComponent) { return; } var inst = this._instance; if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) { inst._calledComponentWillUnmount = true; if (safely) { if (!skipLifecycle) { var name = this.getName() + '.componentWillUnmount()'; ReactErrorUtils_1.invokeGuardedCallbackAndCatchFirstError(name, inst.componentWillUnmount, inst); } } else { { measureLifeCyclePerf(function () { return inst.componentWillUnmount(); }, this._debugID, 'componentWillUnmount'); } } } if (this._renderedComponent) { ReactReconciler_1.unmountComponent(this._renderedComponent, safely, skipLifecycle); this._renderedNodeType = null; this._renderedComponent = null; this._instance = null; } // Reset pending fields // Even if this component is scheduled for another update in ReactUpdates, // it would still be ignored because these fields are reset. this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._pendingCallbacks = null; this._pendingElement = null; // These fields do not really need to be reset since this object is no // longer accessible. this._context = null; this._rootNodeID = 0; this._topLevelWrapper = null; // Delete the reference from the instance to this internal representation // which allow the internals to be properly cleaned up even if the user // leaks a reference to the public instance. ReactInstanceMap_1.remove(inst); // Some existing components rely on inst.props even after they've been // destroyed (in event handlers). // TODO: inst.props = null; // TODO: inst.state = null; // TODO: inst.context = null; }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function (context) { var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject_1; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function (context) { var maskedContext = this._maskContext(context); { var Component = this._currentElement.type; if (Component.contextTypes) { this._checkContextTypes(Component.contextTypes, maskedContext, 'context'); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function (currentContext) { var Component = this._currentElement.type; var inst = this._instance; var childContext; if (typeof inst.getChildContext === 'function') { { ReactInstrumentation.debugTool.onBeginProcessingChildContext(); try { childContext = inst.getChildContext(); } finally { ReactInstrumentation.debugTool.onEndProcessingChildContext(); } } !(typeof Component.childContextTypes === 'object') ? invariant_1(false, '%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().', this.getName() || 'ReactCompositeComponent') : void 0; { this._checkContextTypes(Component.childContextTypes, childContext, 'child context'); } for (var name in childContext) { !(name in Component.childContextTypes) ? invariant_1(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : void 0; } return index({}, currentContext, childContext); } else { { var componentName = this.getName(); if (!warningAboutMissingGetChildContext[componentName]) { warningAboutMissingGetChildContext[componentName] = true; warning_1(!Component.childContextTypes, '%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName); } } } return currentContext; }, /** * Assert that the context types are valid * * @param {object} typeSpecs Map of context field to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkContextTypes: function (typeSpecs, values, location) { { ReactDebugCurrentFrame.current = this._debugID; checkPropTypes_1(typeSpecs, values, location, this.getName(), ReactDebugCurrentFrame.getStackAddendum); ReactDebugCurrentFrame.current = null; } }, receiveComponent: function (nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (transaction) { if (this._pendingElement != null) { ReactReconciler_1.receiveComponent(this, this._pendingElement, transaction, this._context); } else if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } else { var callbacks = this._pendingCallbacks; this._pendingCallbacks = null; if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.getReactMountReady().enqueue(callbacks[j], this.getPublicInstance()); } } this._updateBatchNumber = null; } }, /** * Perform an update to a mounted component. The componentWillReceiveProps and * shouldComponentUpdate methods are called, then (assuming the update isn't * skipped) the remaining update lifecycle methods are called and the DOM * representation is updated. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevParentElement * @param {ReactElement} nextParentElement * @internal * @overridable */ updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { var inst = this._instance; !(inst != null) ? invariant_1(false, 'Attempted to update component `%s` that has already been unmounted (or failed to mount).', this.getName() || 'ReactCompositeComponent') : void 0; var willReceive = false; var nextContext; // Determine if the context has changed or not if (this._context === nextUnmaskedContext) { nextContext = inst.context; } else { nextContext = this._processContext(nextUnmaskedContext); willReceive = true; } var prevProps = prevParentElement.props; var nextProps = nextParentElement.props; // Not a simple state update but a props update if (prevParentElement !== nextParentElement) { willReceive = true; } // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. if (willReceive && inst.componentWillReceiveProps) { var beforeState = inst.state; { measureLifeCyclePerf(function () { return inst.componentWillReceiveProps(nextProps, nextContext); }, this._debugID, 'componentWillReceiveProps'); } var afterState = inst.state; if (beforeState !== afterState) { inst.state = beforeState; inst.updater.enqueueReplaceState(inst, afterState); { warning_1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', this.getName() || 'ReactCompositeComponent'); } } } // If updating happens to enqueue any new updates, we shouldn't execute new // callbacks until the next render happens, so stash the callbacks first. var callbacks = this._pendingCallbacks; this._pendingCallbacks = null; var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = true; if (!this._pendingForceUpdate) { var prevState = inst.state; shouldUpdate = willReceive || nextState !== prevState; if (inst.shouldComponentUpdate) { { shouldUpdate = measureLifeCyclePerf(function () { return inst.shouldComponentUpdate(nextProps, nextState, nextContext); }, this._debugID, 'shouldComponentUpdate'); } } else { if (this._compositeType === ReactCompositeComponentTypes$1.PureClass) { shouldUpdate = !shallowEqual_1(prevProps, nextProps) || !shallowEqual_1(inst.state, nextState); } } } { warning_1(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent'); } this._updateBatchNumber = null; if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext); } else { // If it's determined that a component should not update, we still want // to set props and state but we shortcut the rest of the update. this._currentElement = nextParentElement; this._context = nextUnmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; } if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.getReactMountReady().enqueue(callbacks[j], this.getPublicInstance()); } } }, _processPendingState: function (props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = replace ? queue[0] : inst.state; var dontMutate = true; for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial; if (partialState) { if (dontMutate) { dontMutate = false; nextState = index({}, nextState, partialState); } else { index(nextState, partialState); } } } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { var _this2 = this; var inst = this._instance; var hasComponentDidUpdate = !!inst.componentDidUpdate; var prevProps; var prevState; if (hasComponentDidUpdate) { prevProps = inst.props; prevState = inst.state; } if (inst.componentWillUpdate) { { measureLifeCyclePerf(function () { return inst.componentWillUpdate(nextProps, nextState, nextContext); }, this._debugID, 'componentWillUpdate'); } } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; if (inst.unstable_handleError) { this._updateRenderedComponentWithErrorHandling(transaction, unmaskedContext); } else { this._updateRenderedComponent(transaction, unmaskedContext); } if (hasComponentDidUpdate) { { transaction.getReactMountReady().enqueue(function () { measureLifeCyclePerf(inst.componentDidUpdate.bind(inst, prevProps, prevState), _this2._debugID, 'componentDidUpdate'); }); } } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponentWithErrorHandling: function (transaction, context) { var checkpoint = transaction.checkpoint(); try { this._updateRenderedComponent(transaction, context); } catch (e) { // Roll back to checkpoint, handle error (which may add items to the transaction), // and take a new checkpoint transaction.rollback(checkpoint); this._instance.unstable_handleError(e); if (this._pendingStateQueue) { this._instance.state = this._processPendingState(this._instance.props, this._instance.context); } checkpoint = transaction.checkpoint(); // Gracefully update to a clean state this._updateRenderedComponentWithNextElement(transaction, context, null, true /* safely */ ); // Try again - we've informed the component about the error, so they can render an error message this time. // If this throws again, the error will bubble up (and can be caught by a higher error boundary). this._updateRenderedComponent(transaction, context); } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function (transaction, context) { var nextRenderedElement = this._renderValidatedComponent(); this._updateRenderedComponentWithNextElement(transaction, context, nextRenderedElement, false /* safely */ ); }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponentWithNextElement: function (transaction, context, nextRenderedElement, safely) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var debugID = 0; { debugID = this._debugID; } if (shouldUpdateReactComponent_1(prevRenderedElement, nextRenderedElement)) { ReactReconciler_1.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); } else { var oldHostNode = ReactReconciler_1.getHostNode(prevComponentInstance); if (!ReactFeatureFlags_1.prepareNewChildrenBeforeUnmountInStack) { ReactReconciler_1.unmountComponent(prevComponentInstance, safely, false /* skipLifecycle */ ); } var nodeType = ReactNodeTypes_1.getType(nextRenderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes_1.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var nextMarkup = ReactReconciler_1.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context), debugID); if (ReactFeatureFlags_1.prepareNewChildrenBeforeUnmountInStack) { ReactReconciler_1.unmountComponent(prevComponentInstance, safely, false /* skipLifecycle */ ); } { if (debugID !== 0) { var childDebugIDs = child._debugID !== 0 ? [child._debugID] : []; ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs); } } this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance); } }, /** * Overridden in shallow rendering. * * @protected */ _replaceNodeWithMarkup: function (oldHostNode, nextMarkup, prevInstance) { ReactComponentEnvironment_1.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function () { var inst = this._instance; var renderedElement; { renderedElement = measureLifeCyclePerf(function () { return inst.render(); }, this._debugID, 'render'); } { // We allow auto-mocks to proceed as if they're returning null. if (renderedElement === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedElement = null; } } return renderedElement; }, /** * @private */ _renderValidatedComponent: function () { var renderedElement; if ('development' !== 'production' || this._compositeType !== ReactCompositeComponentTypes$1.StatelessFunctional) { ReactCurrentOwner$1.current = this; try { renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner$1.current = null; } } else { renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); } !( // TODO: An `isValidNode` function would probably be more appropriate renderedElement === null || renderedElement === false || React.isValidElement(renderedElement)) ? invariant_1(false, '%s.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : void 0; return renderedElement; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function (ref, component) { var inst = this.getPublicInstance(); !(inst != null) ? invariant_1(false, 'Stateless function components cannot have refs.') : void 0; var publicComponentInstance = component.getPublicInstance(); var refs = inst.refs === emptyObject_1 ? inst.refs = {} : inst.refs; refs[ref] = publicComponentInstance; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function (ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function () { var type = this._currentElement.type; var constructor = this._instance && this._instance.constructor; return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function () { var inst = this._instance; if (this._compositeType === ReactCompositeComponentTypes$1.StatelessFunctional) { return null; } return inst; }, // Stub _instantiateReactComponent: null }; var ReactCompositeComponent_1 = ReactCompositeComponent; /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEmptyComponent */ var emptyComponentFactory; var ReactEmptyComponentInjection = { injectEmptyComponentFactory: function (factory) { emptyComponentFactory = factory; } }; var ReactEmptyComponent = { create: function (instantiate) { return emptyComponentFactory(instantiate); } }; ReactEmptyComponent.injection = ReactEmptyComponentInjection; var ReactEmptyComponent_1 = ReactEmptyComponent; var genericComponentClass = null; var textComponentClass = null; var ReactHostComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function (componentClass) { genericComponentClass = componentClass; }, // This accepts a text component class that takes the text string to be // rendered as props. injectTextComponentClass: function (componentClass) { textComponentClass = componentClass; } }; /** * Get a host internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { !genericComponentClass ? invariant_1(false, 'There is no registered component for the tag %s', element.type) : void 0; return new genericComponentClass(element); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var ReactHostComponent = { createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactHostComponentInjection }; var ReactHostComponent_1 = ReactHostComponent; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getNextDebugID * */ var nextDebugID = 1; function getNextDebugID() { return nextDebugID++; } var getNextDebugID_1 = getNextDebugID; // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function (element) { this.construct(element); }; function getDeclarationErrorAddendum$2(owner) { if (owner) { var name = owner.getName(); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; } /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @param {boolean} shouldHaveDebugID * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node, shouldHaveDebugID) { var instance; if (node === null || node === false) { instance = ReactEmptyComponent_1.create(instantiateReactComponent); } else if (typeof node === 'object') { var element = node; var type = element.type; if (typeof type !== 'function' && typeof type !== 'string') { var info = ''; { if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in."; } } info += getDeclarationErrorAddendum$2(element._owner); invariant_1(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', type == null ? type : typeof type, info); } // Special case string values if (typeof element.type === 'string') { instance = ReactHostComponent_1.createInternalComponent(element); } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // representations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); // We renamed this. Allow the old name for compat. :( if (!instance.getHostNode) { instance.getHostNode = instance.getNativeNode; } } else { instance = new ReactCompositeComponentWrapper(element); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactHostComponent_1.createInstanceForText(node); } else { invariant_1(false, 'Encountered invalid React node of type %s', typeof node); } { warning_1(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getHostNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.'); } // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; { instance._debugID = shouldHaveDebugID ? getNextDebugID_1() : 0; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } index(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent_1, { _instantiateReactComponent: instantiateReactComponent }); var instantiateReactComponent_1 = instantiateReactComponent; /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElementSymbol * */ // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; var ReactElementSymbol = REACT_ELEMENT_TYPE; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getIteratorFn * */ /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } var getIteratorFn_1 = getIteratorFn; { var getCurrentStackAddendum = ReactGlobalSharedState_1.ReactComponentTreeHook.getCurrentStackAddendum; } var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * This is inlined from ReactElement since this file is shared between * isomorphic and renderers. We could extract this to a * */ /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils_1.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseStackChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || // The following is inlined from ReactElement. This means we can optimize // some checks. React Fiber also inlines this logic for similar purposes. type === 'object' && children.$$typeof === ReactElementSymbol) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseStackChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn_1(children); if (iteratorFn) { { // Warn about using Maps as children if (iteratorFn === children.entries) { warning_1(didWarnAboutMaps, 'Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.%s', getCurrentStackAddendum()); didWarnAboutMaps = true; } } var iterator = iteratorFn.call(children); var step; var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseStackChildrenImpl(child, nextName, callback, traverseContext); } } else if (type === 'object') { var addendum = ''; { addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentStackAddendum(); } var childrenString = '' + children; invariant_1(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum); } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseStackChildren(this.props.children, ...)` * - `traverseStackChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseStackChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseStackChildrenImpl(children, '', callback, traverseContext); } var traverseStackChildren_1 = traverseStackChildren; var ReactComponentTreeHook$2; if (typeof process !== 'undefined' && process.env && 'development' === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook$2 = ReactGlobalSharedState_1.ReactComponentTreeHook; } function instantiateChild(childInstances, child, name, selfDebugID) { // We found a component instance. var keyUnique = childInstances[name] === undefined; { if (!ReactComponentTreeHook$2) { ReactComponentTreeHook$2 = ReactGlobalSharedState_1.ReactComponentTreeHook; } if (!keyUnique) { warning_1(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils_1.unescape(name), ReactComponentTreeHook$2.getStackAddendumByID(selfDebugID)); } } if (child != null && keyUnique) { childInstances[name] = instantiateReactComponent_1(child, true); } } /** * ReactChildReconciler provides helpers for initializing or updating a set of * children. Its output is suitable for passing it onto ReactMultiChild which * does diffed reordering and insertion. */ var ReactChildReconciler = { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildNodes Nested child maps. * @return {?object} A set of child instances. * @internal */ instantiateChildren: function (nestedChildNodes, transaction, context, selfDebugID) // 0 in production and for roots { if (nestedChildNodes == null) { return null; } var childInstances = {}; { traverseStackChildren_1(nestedChildNodes, function (childInsts, child, name) { return instantiateChild(childInsts, child, name, selfDebugID); }, childInstances); } return childInstances; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextChildren Flat child element maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function (prevChildren, nextChildren, mountImages, removedNodes, transaction, hostParent, hostContainerInfo, context, selfDebugID) // 0 in production and for roots { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. if (!nextChildren && !prevChildren) { return; } var name; var prevChild; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (prevChild != null && shouldUpdateReactComponent_1(prevElement, nextElement)) { ReactReconciler_1.receiveComponent(prevChild, nextElement, transaction, context); nextChildren[name] = prevChild; } else { if (!ReactFeatureFlags_1.prepareNewChildrenBeforeUnmountInStack && prevChild) { removedNodes[name] = ReactReconciler_1.getHostNode(prevChild); ReactReconciler_1.unmountComponent(prevChild, false /* safely */ , false /* skipLifecycle */ ); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent_1(nextElement, true); nextChildren[name] = nextChildInstance; // Creating mount image now ensures refs are resolved in right order // (see https://github.com/facebook/react/pull/7101 for explanation). var nextChildMountImage = ReactReconciler_1.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context, selfDebugID); mountImages.push(nextChildMountImage); if (ReactFeatureFlags_1.prepareNewChildrenBeforeUnmountInStack && prevChild) { removedNodes[name] = ReactReconciler_1.getHostNode(prevChild); ReactReconciler_1.unmountComponent(prevChild, false /* safely */ , false /* skipLifecycle */ ); } } } // Unmount children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { prevChild = prevChildren[name]; removedNodes[name] = ReactReconciler_1.getHostNode(prevChild); ReactReconciler_1.unmountComponent(prevChild, false /* safely */ , false /* skipLifecycle */ ); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function (renderedChildren, safely, skipLifecycle) { for (var name in renderedChildren) { if (renderedChildren.hasOwnProperty(name)) { var renderedChild = renderedChildren[name]; ReactReconciler_1.unmountComponent(renderedChild, safely, skipLifecycle); } } } }; var ReactChildReconciler_1 = ReactChildReconciler; var ReactComponentTreeHook$3; if (typeof process !== 'undefined' && process.env && 'development' === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook$3 = ReactGlobalSharedState_1.ReactComponentTreeHook; } /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. * @param {number=} selfDebugID Optional debugID of the current internal instance. */ function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) { // We found a component instance. if (traverseContext && typeof traverseContext === 'object') { var result = traverseContext; var keyUnique = result[name] === undefined; { if (!ReactComponentTreeHook$3) { ReactComponentTreeHook$3 = ReactGlobalSharedState_1.ReactComponentTreeHook; } if (!keyUnique) { warning_1(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils_1.unescape(name), ReactComponentTreeHook$3.getStackAddendumByID(selfDebugID)); } } if (keyUnique && child != null) { result[name] = child; } } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenStackChildren(children, selfDebugID) { if (children == null) { return children; } var result = {}; { traverseStackChildren_1(children, function (traverseContext, child, name) { return flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID); }, result); } return result; } var flattenStackChildren_1 = flattenStackChildren; var ReactCurrentOwner = ReactGlobalSharedState_1.ReactCurrentOwner; /** * Make an update for markup to be rendered and inserted at a supplied index. * * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: 'INSERT_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for moving an existing element to another index. * * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: 'MOVE_EXISTING', content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler_1.getHostNode(child), toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for removing an element at an index. * * @param {number} fromIndex Index of the element to remove. * @private */ function makeRemove(child, node) { // NOTE: Null values reduce hidden classes. return { type: 'REMOVE_NODE', content: null, fromIndex: child._mountIndex, fromNode: node, toIndex: null, afterNode: null }; } /** * Make an update for setting the markup of a node. * * @param {string} markup Markup that renders into an element. * @private */ function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { type: 'SET_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Make an update for setting the text content. * * @param {string} textContent Text content to set. * @private */ function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { type: 'TEXT_CONTENT', content: textContent, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Push an update, if any, onto the queue. Creates a new queue if none is * passed and always returns the queue. Mutative. */ function enqueue(queue, update) { if (update) { queue = queue || []; queue.push(update); } return queue; } /** * Processes any enqueued updates. * * @private */ function processQueue(inst, updateQueue) { ReactComponentEnvironment_1.processChildrenUpdates(inst, updateQueue); } var setChildrenForInstrumentation = emptyFunction_1; { var getDebugID = function (inst) { if (!inst._debugID) { // Check for ART-like instances. TODO: This is silly/gross. var internal; if (internal = ReactInstanceMap_1.get(inst)) { inst = internal; } } return inst._debugID; }; setChildrenForInstrumentation = function (children) { var debugID = getDebugID(this); // TODO: React Native empty components are also multichild. // This means they still get into this method but don't have _debugID. if (debugID !== 0) { ReactInstrumentation.debugTool.onSetChildren(debugID, children ? Object.keys(children).map(function (key) { return children[key]._debugID; }) : []); } }; } /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. */ var ReactMultiChild = { _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { { var selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; return ReactChildReconciler_1.instantiateChildren(nestedChildren, transaction, context, selfDebugID); } finally { ReactCurrentOwner.current = null; } } } return ReactChildReconciler_1.instantiateChildren(nestedChildren, transaction, context); }, _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context) { var nextChildren; var selfDebugID = 0; { selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; nextChildren = flattenStackChildren_1(nextNestedChildrenElements, selfDebugID); } finally { ReactCurrentOwner.current = null; } ReactChildReconciler_1.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID); return nextChildren; } } nextChildren = flattenStackChildren_1(nextNestedChildrenElements, selfDebugID); ReactChildReconciler_1.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID); return nextChildren; }, /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function (nestedChildren, transaction, context) { var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); this._renderedChildren = children; var mountImages = []; var index = 0; for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; var selfDebugID = 0; { selfDebugID = getDebugID(this); } var mountImage = ReactReconciler_1.mountComponent(child, transaction, this, this._hostContainerInfo, context, selfDebugID); child._mountIndex = index++; mountImages.push(mountImage); } } { setChildrenForInstrumentation.call(this, children); } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function (nextContent) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler_1.unmountChildren(prevChildren, false /* safely */ , false /* skipLifecycle */ ); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { invariant_1(false, 'updateTextContent called on non-empty component.'); } } // Set new text content. var updates = [makeTextContent(nextContent)]; processQueue(this, updates); }, /** * Replaces any rendered children with a markup string. * * @param {string} nextMarkup String of markup. * @internal */ updateMarkup: function (nextMarkup) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler_1.unmountChildren(prevChildren, false /* safely */ , false /* skipLifecycle */ ); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { invariant_1(false, 'updateTextContent called on non-empty component.'); } } var updates = [makeSetMarkup(nextMarkup)]; processQueue(this, updates); }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function (nextNestedChildrenElements, transaction, context) { // Hook used by React ART this._updateChildren(nextNestedChildrenElements, transaction, context); }, /** * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function (nextNestedChildrenElements, transaction, context) { var prevChildren = this._renderedChildren; var removedNodes = {}; var mountImages = []; var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context); if (!nextChildren && !prevChildren) { return; } var updates = null; var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var nextIndex = 0; var lastIndex = 0; // `nextMountIndex` will increment for each newly mounted child. var nextMountIndex = 0; var lastPlacedNode = null; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (prevChild === nextChild) { updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); // The `removedNodes` loop below will actually remove the child. } // The child must be instantiated before it's mounted. updates = enqueue(updates, this._mountChildAtIndex(nextChild, mountImages[nextMountIndex], lastPlacedNode, nextIndex, transaction, context)); nextMountIndex++; } nextIndex++; lastPlacedNode = ReactReconciler_1.getHostNode(nextChild); } // Remove children that are no longer present. for (name in removedNodes) { if (removedNodes.hasOwnProperty(name)) { updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name])); } } if (updates) { processQueue(this, updates); } this._renderedChildren = nextChildren; { setChildrenForInstrumentation.call(this, nextChildren); } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. It does not actually perform any * backend operations. * * @internal */ unmountChildren: function (safely, skipLifecycle) { var renderedChildren = this._renderedChildren; ReactChildReconciler_1.unmountChildren(renderedChildren, safely, skipLifecycle); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function (child, afterNode, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { return makeMove(child, afterNode, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function (child, afterNode, mountImage) { return makeInsertMarkup(mountImage, afterNode, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function (child, node) { return makeRemove(child, node); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildAtIndex: function (child, mountImage, afterNode, index, transaction, context) { child._mountIndex = index; return this.createChild(child, afterNode, mountImage); }, /** * Unmounts a rendered child. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @private */ _unmountChild: function (child, node) { var update = this.removeChild(child, node); child._mountIndex = null; return update; } }; var ReactMultiChild_1 = ReactMultiChild; var OBSERVED_ERROR = {}; /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM updates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var TransactionImpl = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function () { this.transactionWrappers = this.getTransactionWrappers(); if (this.wrapperInitData) { this.wrapperInitData.length = 0; } else { this.wrapperInitData = []; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function () { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. The optional arguments helps prevent the need * to bind in many cases. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} a Argument to pass to the method. * @param {Object?=} b Argument to pass to the method. * @param {Object?=} c Argument to pass to the method. * @param {Object?=} d Argument to pass to the method. * @param {Object?=} e Argument to pass to the method. * @param {Object?=} f Argument to pass to the method. * * @return {*} Return value from `method`. */ perform: function (method, scope, a, b, c, d, e, f) { !!this.isInTransaction() ? invariant_1(false, 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.') : void 0; var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) {} } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function (startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) {} } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function (startIndex) { !this.isInTransaction() ? invariant_1(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : void 0; var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== OBSERVED_ERROR && wrapper.close) { wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) {} } } } this.wrapperInitData.length = 0; } }; var Transaction = TransactionImpl; var dirtyComponents = []; var updateBatchNumber = 0; var batchingStrategy = null; function ensureInjected() { !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? invariant_1(false, 'ReactUpdates: must inject a reconcile transaction class and batching strategy') : void 0; } var NESTED_UPDATES = { initialize: function () { this.dirtyComponentsLength = dirtyComponents.length; }, close: function () { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var TRANSACTION_WRAPPERS$1 = [NESTED_UPDATES]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */true); } index(ReactUpdatesFlushTransaction.prototype, Transaction, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS$1; }, destructor: function () { this.dirtyComponentsLength = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function (method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }); PooledClass_1.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates$1(callback, a, b, c, d, e) { ensureInjected(); return batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; !(len === dirtyComponents.length) ? invariant_1(false, 'Expected flush transaction\'s stored dirty-components length (%s) to match dirty-components array length (%s).', len, dirtyComponents.length) : void 0; // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); // Any updates enqueued while reconciling must be performed after this entire // batch. Otherwise, if dirtyComponents is [A, B] where A has children B and // C, B could update twice in a single batch if C's render enqueues an update // to B (since B would have already updated, we should skip it, and the only // way we can know to do so is by checking the batch counter). updateBatchNumber++; for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; var markerName; if (ReactFeatureFlags_1.logTopLevelRenders) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. if (component._currentElement.type.isReactTopLevelWrapper) { namedComponent = component._renderedComponent; } markerName = 'React update: ' + namedComponent.getName(); console.time(markerName); } ReactReconciler_1.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber); if (markerName) { console.timeEnd(markerName); } } } var flushBatchedUpdates = function () { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks. while (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } }; /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate$1(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate$1, component); return; } dirtyComponents.push(component); if (component._updateBatchNumber == null) { component._updateBatchNumber = updateBatchNumber + 1; } } var ReactUpdatesInjection = { injectReconcileTransaction: function (ReconcileTransaction) { !ReconcileTransaction ? invariant_1(false, 'ReactUpdates: must provide a reconcile transaction class') : void 0; ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function (_batchingStrategy) { !_batchingStrategy ? invariant_1(false, 'ReactUpdates: must provide a batching strategy') : void 0; !(typeof _batchingStrategy.batchedUpdates === 'function') ? invariant_1(false, 'ReactUpdates: must provide a batchedUpdates() function') : void 0; !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? invariant_1(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : void 0; batchingStrategy = _batchingStrategy; }, getBatchingStrategy: function () { return batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates$1, enqueueUpdate: enqueueUpdate$1, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection }; var ReactUpdates_1 = ReactUpdates; var ReactCurrentOwner$2 = ReactGlobalSharedState_1.ReactCurrentOwner; { var warning$4 = warning_1; var warnOnInvalidCallback = function (callback, callerName) { warning$4(callback === null || typeof callback === 'function', '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, '' + callback); }; } function enqueueUpdate(internalInstance) { ReactUpdates_1.enqueueUpdate(internalInstance); } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { var internalInstance = ReactInstanceMap_1.get(publicInstance); if (!internalInstance) { { var ctor = publicInstance.constructor; warning$4(false, 'Can only update a mounted or mounting component. This usually means ' + 'you called setState, replaceState, or forceUpdate on an unmounted ' + 'component. This is a no-op.\n\nPlease check the code for the ' + '%s component.', ctor && (ctor.displayName || ctor.name) || 'ReactClass'); } return null; } { warning$4(ReactCurrentOwner$2.current == null, 'Cannot update during an existing state transition (such as within ' + "`render` or another component's constructor). Render methods should " + 'be a pure function of props and state; constructor side-effects are ' + 'an anti-pattern, but can be moved to `componentWillMount`.'); } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { { var owner = ReactCurrentOwner$2.current; if (owner !== null) { warning$4(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component'); owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap_1.get(publicInstance); if (internalInstance) { // During componentWillMount and render this will still be null but after // that will always render to something. At least for now. So we can use // this hack. return !!internalInstance._renderedComponent; } else { return false; } }, enqueueCallbackInternal: function (internalInstance, callback) { if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueForceUpdate: function (publicInstance, callback, callerName) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); if (!internalInstance) { return; } callback = callback === undefined ? null : callback; if (callback !== null) { { warnOnInvalidCallback(callback, callerName); } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @param {?function} callback Called after state is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueReplaceState: function (publicInstance, completeState, callback, callerName) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; callback = callback === undefined ? null : callback; if (callback !== null) { { warnOnInvalidCallback(callback, callerName); } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } } enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after state is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueSetState: function (publicInstance, partialState, callback, callerName) { { ReactInstrumentation.debugTool.onSetState(); warning$4(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().'); } var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); callback = callback === undefined ? null : callback; if (callback !== null) { { warnOnInvalidCallback(callback, callerName); } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } } enqueueUpdate(internalInstance); }, enqueueElementInternal: function (internalInstance, nextElement, nextContext) { internalInstance._pendingElement = nextElement; // TODO: introduce _pendingContext instead of setting it directly. internalInstance._context = nextContext; enqueueUpdate(internalInstance); } }; var ReactUpdateQueue_1 = ReactUpdateQueue; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function warnNoop(publicInstance, callerName) { { var constructor = publicInstance.constructor; warning_1(false, '%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass'); } } /** * This is the update queue used for server rendering. * It delegates to ReactUpdateQueue while server rendering is in progress and * switches to ReactNoopUpdateQueue after the transaction has completed. * @class ReactServerUpdateQueue * @param {Transaction} transaction */ var ReactServerUpdateQueue = function () { function ReactServerUpdateQueue(transaction) { _classCallCheck(this, ReactServerUpdateQueue); this.transaction = transaction; } /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ ReactServerUpdateQueue.prototype.isMounted = function isMounted(publicInstance) { return false; }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ ReactServerUpdateQueue.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance, callback, callerName) { if (this.transaction.isInTransaction()) { ReactUpdateQueue_1.enqueueForceUpdate(publicInstance, callback, callerName); } else { warnNoop(publicInstance, 'forceUpdate'); } }; /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object|function} completeState Next state. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ ReactServerUpdateQueue.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState, callback, callerName) { if (this.transaction.isInTransaction()) { ReactUpdateQueue_1.enqueueReplaceState(publicInstance, completeState, callback, callerName); } else { warnNoop(publicInstance, 'replaceState'); } }; /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object|function} partialState Next partial state to be merged with state. * @internal */ ReactServerUpdateQueue.prototype.enqueueSetState = function enqueueSetState(publicInstance, partialState, callback, callerName) { if (this.transaction.isInTransaction()) { ReactUpdateQueue_1.enqueueSetState(publicInstance, partialState, callback, callerName); } else { warnNoop(publicInstance, 'setState'); } }; return ReactServerUpdateQueue; }(); var ReactServerUpdateQueue_1 = ReactServerUpdateQueue; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = []; { TRANSACTION_WRAPPERS.push({ initialize: ReactInstrumentation.debugTool.onBeginFlush, close: ReactInstrumentation.debugTool.onEndFlush }); } var noopCallbackQueue = { enqueue: function () {} }; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.useCreateElement = false; this.updateQueue = new ReactServerUpdateQueue_1(this); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap procedures. */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return noopCallbackQueue; }, /** * @return {object} The queue to collect React async events. */ getUpdateQueue: function () { return this.updateQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () {}, checkpoint: function () {}, rollback: function () {} }; index(ReactServerRenderingTransaction.prototype, Transaction, Mixin); PooledClass_1.addPoolingTo(ReactServerRenderingTransaction); var ReactServerRenderingTransaction_1 = ReactServerRenderingTransaction; var validateDOMNesting = emptyFunction_1; { var _require$5 = ReactDebugCurrentFiber_1, getCurrentFiberStackAddendum$1 = _require$5.getCurrentFiberStackAddendum; // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; var updatedAncestorInfo = function (oldInfo, tag, instance) { var ancestorInfo = index({}, oldInfo || emptyAncestorInfo); var info = { tag: tag, instance: instance }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.current = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body'; case '#document': return tag === 'html'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'body': case 'caption': case 'col': case 'colgroup': case 'frame': case 'head': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; /** * Given a ReactCompositeComponent instance, return a list of its recursive * owners, starting at the root and ending with the instance itself. */ var findOwnerStack = function (instance) { if (!instance) { return []; } var stack = []; do { stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }; var getOwnerInfo = function (childInstance, childTag, ancestorInstance, ancestorTag, isParent) { var childOwner = childInstance && childInstance._currentElement._owner; var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; var childOwners = findOwnerStack(childOwner); var ancestorOwners = findOwnerStack(ancestorOwner); var minStackLen = Math.min(childOwners.length, ancestorOwners.length); var i; var deepestCommon = -1; for (i = 0; i < minStackLen; i++) { if (childOwners[i] === ancestorOwners[i]) { deepestCommon = i; } else { break; } } var UNKNOWN = '(unknown)'; var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { return getComponentName_1(inst) || UNKNOWN; }); var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { return getComponentName_1(inst) || UNKNOWN; }); var ownerInfo = [].concat( // If the parent and child instances have a common owner ancestor, start // with that -- otherwise we just start with the parent's owners. deepestCommon !== -1 ? getComponentName_1(childOwners[deepestCommon]) || UNKNOWN : [], ancestorOwnerNames, ancestorTag, // If we're warning about an invalid (non-parent) ancestry, add '...' isParent ? [] : ['...'], childOwnerNames, childTag).join(' > '); return ownerInfo; }; var didWarn = {}; validateDOMNesting = function (childTag, childText, childInstance, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; if (childText != null) { warning_1(childTag == null, 'validateDOMNesting: when childText is passed, childTag should be null'); childTag = '#text'; } var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var invalidParentOrAncestor = invalidParent || invalidAncestor; if (!invalidParentOrAncestor) { return; } var ancestorInstance = invalidParentOrAncestor.instance; var ancestorTag = invalidParentOrAncestor.tag; var addendum; if (childInstance != null) { addendum = ' See ' + getOwnerInfo(childInstance, childTag, ancestorInstance, ancestorTag, !!invalidParent) + '.'; } else { addendum = getCurrentFiberStackAddendum$1(); } var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; var tagDisplayName = childTag; var whitespaceInfo = ''; if (childTag === '#text') { if (/\S/.test(childText)) { tagDisplayName = 'Text nodes'; } else { tagDisplayName = 'Whitespace text nodes'; whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.'; } } else { tagDisplayName = '<' + childTag + '>'; } if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; } warning_1(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info, addendum); } else { warning_1(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.%s', tagDisplayName, ancestorTag, addendum); } }; validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; // For testing validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); }; } var validateDOMNesting_1 = validateDOMNesting; var DOCUMENT_FRAGMENT_NODE$1 = HTMLNodeType_1.DOCUMENT_FRAGMENT_NODE; var didWarnShadyDOM = false; var Flags$1 = ReactDOMComponentFlags_1; var getNode = ReactDOMComponentTree_1.getNodeFromInstance; var listenTo = ReactBrowserEventEmitter_1.listenTo; var registrationNameModules = EventPluginRegistry_1.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = { string: true, number: true }; var STYLE = 'style'; var HTML = '__html'; var RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null }; function getDeclarationErrorAddendum(internalInstance) { if (internalInstance) { var owner = internalInstance._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return '\n\nThis DOM node was rendered by `' + name + '`.'; } } } return ''; } /** * @param {object} component * @param {?object} props */ function assertValidProps(component, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (voidElementTags[component._tag]) { !(props.children == null && props.dangerouslySetInnerHTML == null) ? invariant_1(false, '%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s', component._tag, getDeclarationErrorAddendum(component)) : void 0; } if (props.dangerouslySetInnerHTML != null) { !(props.children == null) ? invariant_1(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : void 0; !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? invariant_1(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.') : void 0; } { warning_1(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.'); warning_1(props.suppressContentEditableWarning || !props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.'); warning_1(props.onFocusIn == null && props.onFocusOut == null, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.'); } !(props.style == null || typeof props.style === 'object') ? invariant_1(false, 'The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}} when using JSX.%s', getDeclarationErrorAddendum(component)) : void 0; } function ensureListeningTo(inst, registrationName, transaction) { if (transaction instanceof ReactServerRenderingTransaction_1) { return; } var containerInfo = inst._hostContainerInfo; var isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOCUMENT_FRAGMENT_NODE$1; var doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument; listenTo(registrationName, doc); } function inputPostMount() { var inst = this; ReactDOMInput_1.postMountWrapper(inst); } function textareaPostMount() { var inst = this; ReactDOMTextarea_1.postMountWrapper(inst); } function optionPostMount() { var inst = this; ReactDOMOption_1.postMountWrapper(inst); } var setAndValidateContentChildDev = emptyFunction_1; { setAndValidateContentChildDev = function (content) { var hasExistingContent = this._contentDebugID != null; var debugID = this._debugID; // This ID represents the inlined child that has no backing instance: var contentDebugID = -debugID; if (content == null) { if (hasExistingContent) { ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID); } this._contentDebugID = null; return; } validateDOMNesting_1(null, '' + content, this, this._ancestorInfo); this._contentDebugID = contentDebugID; if (hasExistingContent) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(contentDebugID, content); ReactInstrumentation.debugTool.onUpdateComponent(contentDebugID); } else { ReactInstrumentation.debugTool.onBeforeMountComponent(contentDebugID, content, debugID); ReactInstrumentation.debugTool.onMountComponent(contentDebugID); ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]); } }; } // There are so many media events, it makes sense to just // maintain a list rather than create a `trapBubbledEvent` for each var mediaEvents = { topAbort: 'abort', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topSeeked: 'seeked', topSeeking: 'seeking', topStalled: 'stalled', topSuspend: 'suspend', topTimeUpdate: 'timeupdate', topVolumeChange: 'volumechange', topWaiting: 'waiting' }; function trackInputValue() { inputValueTracking_1.track(this); } function trapClickOnNonInteractiveElement() { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html // Just set it using the onclick property so that we don't have to manage any // bookkeeping for it. Not sure if we need to clear it when the listener is // removed. // TODO: Only do this for the relevant Safaris maybe? var node = getNode(this); node.onclick = emptyFunction_1; } function trapBubbledEventsLocal() { var inst = this; // If a component renders to null or if another component fatals and causes // the state of the tree to be corrupted, `node` here can be null. !inst._rootNodeID ? invariant_1(false, 'Must be mounted to trap events') : void 0; var node = getNode(inst); !node ? invariant_1(false, 'trapBubbledEvent(...): Requires node to be rendered.') : void 0; switch (inst._tag) { case 'iframe': case 'object': inst._wrapperState.listeners = [ReactBrowserEventEmitter_1.trapBubbledEvent('topLoad', 'load', node)]; break; case 'video': case 'audio': inst._wrapperState.listeners = []; // Create listener for each media event for (var event in mediaEvents) { if (mediaEvents.hasOwnProperty(event)) { inst._wrapperState.listeners.push(ReactBrowserEventEmitter_1.trapBubbledEvent(event, mediaEvents[event], node)); } } break; case 'source': inst._wrapperState.listeners = [ReactBrowserEventEmitter_1.trapBubbledEvent('topError', 'error', node)]; break; case 'img': case 'image': inst._wrapperState.listeners = [ReactBrowserEventEmitter_1.trapBubbledEvent('topError', 'error', node), ReactBrowserEventEmitter_1.trapBubbledEvent('topLoad', 'load', node)]; break; case 'form': inst._wrapperState.listeners = [ReactBrowserEventEmitter_1.trapBubbledEvent('topReset', 'reset', node), ReactBrowserEventEmitter_1.trapBubbledEvent('topSubmit', 'submit', node)]; break; case 'input': case 'select': case 'textarea': inst._wrapperState.listeners = [ReactBrowserEventEmitter_1.trapBubbledEvent('topInvalid', 'invalid', node)]; break; case 'details': inst._wrapperState.listeners = [ReactBrowserEventEmitter_1.trapBubbledEvent('topToggle', 'toggle', node)]; break; } } function postUpdateSelectWrapper() { ReactDOMSelect_1.postUpdateWrapper(this); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special-case tags. var omittedCloseTags = { area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true }; var newlineEatingTags = { listing: true, pre: true, textarea: true }; // For HTML, certain tags cannot have children. This has the same purpose as // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = index({ menuitem: true }, omittedCloseTags); // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty$2 = {}.hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty$2.call(validatedTagCache, tag)) { !VALID_TAG_REGEX.test(tag) ? invariant_1(false, 'Invalid tag: %s', tag) : void 0; validatedTagCache[tag] = true; } } function isCustomComponent(tagName, props) { return tagName.indexOf('-') >= 0 || props.is != null; } var globalIdCounter = 1; /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(element) { var tag = element.type; this._currentElement = element; this._tag = tag.toLowerCase(); this._namespaceURI = null; this._renderedChildren = null; this._hostNode = null; this._hostParent = null; this._rootNodeID = 0; this._domID = 0; this._hostContainerInfo = null; this._wrapperState = null; this._topLevelWrapper = null; this._flags = 0; { this._ancestorInfo = null; setAndValidateContentChildDev.call(this, null); } } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?ReactDOMComponent} the parent component instance * @param {?object} info about the host container * @param {object} context * @return {string} The computed markup. */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { this._rootNodeID = globalIdCounter++; this._domID = hostContainerInfo._idCounter++; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var props = this._currentElement.props; switch (this._tag) { case 'audio': case 'form': case 'iframe': case 'img': case 'image': case 'link': case 'object': case 'source': case 'video': case 'details': this._wrapperState = { listeners: null }; transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'input': ReactDOMInput_1.mountWrapper(this, props, hostParent); props = ReactDOMInput_1.getHostProps(this, props); transaction.getReactMountReady().enqueue(trackInputValue, this); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); // For controlled components we always need to ensure we're listening // to onChange. Even if there is no listener. ensureListeningTo(this, 'onChange', transaction); break; case 'option': ReactDOMOption_1.mountWrapper(this, props, hostParent); props = ReactDOMOption_1.getHostProps(this, props); break; case 'select': ReactDOMSelect_1.mountWrapper(this, props, hostParent); props = ReactDOMSelect_1.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); // For controlled components we always need to ensure we're listening // to onChange. Even if there is no listener. ensureListeningTo(this, 'onChange', transaction); break; case 'textarea': ReactDOMTextarea_1.mountWrapper(this, props, hostParent); props = ReactDOMTextarea_1.getHostProps(this, props); transaction.getReactMountReady().enqueue(trackInputValue, this); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); // For controlled components we always need to ensure we're listening // to onChange. Even if there is no listener. ensureListeningTo(this, 'onChange', transaction); break; } assertValidProps(this, props); { var isCustomComponentTag = isCustomComponent(this._tag, props); } // We create tags in the namespace of their parent container, except HTML // tags get no namespace. var namespaceURI; var parentTag; if (hostParent != null) { namespaceURI = hostParent._namespaceURI; parentTag = hostParent._tag; } else if (hostContainerInfo._tag) { namespaceURI = hostContainerInfo._namespaceURI; parentTag = hostContainerInfo._tag; } if (namespaceURI == null || namespaceURI === DOMNamespaces_1.svg && parentTag === 'foreignobject') { namespaceURI = DOMNamespaces_1.html; } if (namespaceURI === DOMNamespaces_1.html) { { warning_1(isCustomComponentTag || this._tag === this._currentElement.type, '<%s /> is using uppercase HTML. Always use lowercase HTML tags ' + 'in React.', this._currentElement.type); } if (this._tag === 'svg') { namespaceURI = DOMNamespaces_1.svg; } else if (this._tag === 'math') { namespaceURI = DOMNamespaces_1.mathml; } } this._namespaceURI = namespaceURI; { var parentInfo; if (hostParent != null) { parentInfo = hostParent._ancestorInfo; } else if (hostContainerInfo._tag) { parentInfo = hostContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting_1(this._tag, null, this, parentInfo); } this._ancestorInfo = validateDOMNesting_1.updatedAncestorInfo(parentInfo, this._tag, this); } var mountImage; var type = this._currentElement.type; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var el; if (namespaceURI === DOMNamespaces_1.html) { if (this._tag === 'script') { // Create the script via .innerHTML so its "parser-inserted" flag is // set to true and it does not execute var div = ownerDocument.createElement('div'); div.innerHTML = '<' + type + '></' + type + '>'; el = div.removeChild(div.firstChild); } else if (props.is) { el = ownerDocument.createElement(type, { is: props.is }); } else { // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug. // See discussion in https://github.com/facebook/react/pull/6896 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240 el = ownerDocument.createElement(type); } } else { el = ownerDocument.createElementNS(namespaceURI, type); } { if (isCustomComponentTag && !didWarnShadyDOM && el.shadyRoot) { var owner = this._currentElement._owner; var name = owner && owner.getName() || 'A component'; warning_1(false, '%s is using shady DOM. Using shady DOM with React can ' + 'cause things to break subtly.', name); didWarnShadyDOM = true; } if (this._namespaceURI === DOMNamespaces_1.html) { warning_1(isCustomComponentTag || Object.prototype.toString.call(el) !== '[object HTMLUnknownElement]', 'The tag <%s> is unrecognized in this browser. ' + 'If you meant to render a React component, start its name with ' + 'an uppercase letter.', this._tag); } } ReactDOMComponentTree_1.precacheNode(this, el); this._flags |= Flags$1.hasCachedChildNodes; if (!this._hostParent) { DOMPropertyOperations_1.setAttributeForRoot(el); } this._updateDOMProperties(null, props, transaction, isCustomComponentTag); var lazyTree = DOMLazyTree_1(el); this._createInitialChildren(transaction, props, context, lazyTree); mountImage = lazyTree; } else { validateDangerousTag(this._tag); var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); var tagContent = this._createContentMarkup(transaction, props, context); if (!tagContent && omittedCloseTags[this._tag]) { mountImage = tagOpen + '/>'; } else { mountImage = tagOpen + '>' + tagContent + '</' + type + '>'; } } switch (this._tag) { case 'input': transaction.getReactMountReady().enqueue(inputPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils_1.focusDOMComponent, this); } break; case 'textarea': transaction.getReactMountReady().enqueue(textareaPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils_1.focusDOMComponent, this); } break; case 'select': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils_1.focusDOMComponent, this); } break; case 'button': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils_1.focusDOMComponent, this); } break; case 'option': transaction.getReactMountReady().enqueue(optionPostMount, this); break; default: if (typeof props.onClick === 'function') { transaction.getReactMountReady().enqueue(trapClickOnNonInteractiveElement, this); } break; } return mountImage; }, /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function (transaction, props) { var ret = '<' + this._currentElement.type; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { if (propValue) { ensureListeningTo(this, propKey, transaction); } } else { if (propKey === STYLE) { if (propValue) { { Object.freeze(propValue); } } propValue = CSSPropertyOperations_1.createMarkupForStyles(propValue, this); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = DOMPropertyOperations_1.createMarkupForCustomAttribute(propKey, propValue); } } else { markup = DOMPropertyOperations_1.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret; } if (!this._hostParent) { ret += ' ' + DOMPropertyOperations_1.createMarkupForRoot(); } ret += ' ' + DOMPropertyOperations_1.createMarkupForID(this._domID); return ret; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function (transaction, props, context) { var ret = ''; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { ret = innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node ret = escapeTextContentForBrowser_1(contentToUse); { setAndValidateContentChildDev.call(this, contentToUse); } } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); ret = mountImages.join(''); } } if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> return '\n' + ret; } else { return ret; } }, _createInitialChildren: function (transaction, props, context, lazyTree) { // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { var innerHTMLContent = innerHTML.__html; if (innerHTMLContent != null && innerHTMLContent !== '') { DOMLazyTree_1.queueHTML(lazyTree, innerHTMLContent); } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; // TODO: Validate that text is allowed as a child of this node if (contentToUse != null) { // Avoid setting textContent when the text is empty. In IE11 setting // textContent on a text area will cause the placeholder to not // show within the textarea until it has been focused and blurred again. // https://github.com/facebook/react/issues/6731#issuecomment-254874553 if (contentToUse !== '') { { setAndValidateContentChildDev.call(this, contentToUse); } DOMLazyTree_1.queueText(lazyTree, contentToUse); } } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); for (var i = 0; i < mountImages.length; i++) { DOMLazyTree_1.queueChild(lazyTree, mountImages[i]); } } } }, /** * Receives a next element and updates the component. * * @internal * @param {ReactElement} nextElement * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context */ receiveComponent: function (nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function (transaction, prevElement, nextElement, context) { var lastProps = prevElement.props; var nextProps = this._currentElement.props; switch (this._tag) { case 'input': lastProps = ReactDOMInput_1.getHostProps(this, lastProps); nextProps = ReactDOMInput_1.getHostProps(this, nextProps); break; case 'option': lastProps = ReactDOMOption_1.getHostProps(this, lastProps); nextProps = ReactDOMOption_1.getHostProps(this, nextProps); break; case 'select': lastProps = ReactDOMSelect_1.getHostProps(this, lastProps); nextProps = ReactDOMSelect_1.getHostProps(this, nextProps); break; case 'textarea': lastProps = ReactDOMTextarea_1.getHostProps(this, lastProps); nextProps = ReactDOMTextarea_1.getHostProps(this, nextProps); break; default: if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') { transaction.getReactMountReady().enqueue(trapClickOnNonInteractiveElement, this); } break; } assertValidProps(this, nextProps); var isCustomComponentTag = isCustomComponent(this._tag, nextProps); this._updateDOMProperties(lastProps, nextProps, transaction, isCustomComponentTag); this._updateDOMChildren(lastProps, nextProps, transaction, context); switch (this._tag) { case 'input': // Update the wrapper around inputs *after* updating props. This has to // happen after `_updateDOMProperties`. Otherwise HTML5 input validations // raise warnings and prevent the new value from being assigned. ReactDOMInput_1.updateWrapper(this); break; case 'textarea': ReactDOMTextarea_1.updateWrapper(this); break; case 'select': // <select> value update needs to occur after <option> children // reconciliation transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); break; } }, /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {object} nextProps * @param {?DOMElement} node */ _updateDOMProperties: function (lastProps, nextProps, transaction, isCustomComponentTag) { var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) { continue; } if (propKey === STYLE) { var lastStyle = lastProps[STYLE]; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } } else if (registrationNameModules.hasOwnProperty(propKey)) { // Do nothing for event names. } else if (isCustomComponent(this._tag, lastProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations_1.deleteValueForAttribute(getNode(this), propKey); } } else if (DOMProperty_1.properties[propKey] || DOMProperty_1.isCustomAttribute(propKey)) { DOMPropertyOperations_1.deleteValueForProperty(getNode(this), propKey); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = lastProps != null ? lastProps[propKey] : undefined; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) { continue; } if (propKey === STYLE) { if (nextProp) { { Object.freeze(nextProp); } } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { if (nextProp) { ensureListeningTo(this, propKey, transaction); } } else if (isCustomComponentTag) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations_1.setValueForAttribute(getNode(this), propKey, nextProp); } } else if (DOMProperty_1.properties[propKey] || DOMProperty_1.isCustomAttribute(propKey)) { var node = getNode(this); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertently setting to a string. This // brings us in line with the same behavior we have on initial render. if (nextProp != null) { DOMPropertyOperations_1.setValueForProperty(node, propKey, nextProp); } else { DOMPropertyOperations_1.deleteValueForProperty(node, propKey); } } } if (styleUpdates) { { ReactInstrumentation.debugTool.onHostOperation({ instanceID: this._debugID, type: 'update styles', payload: styleUpdates }); } CSSPropertyOperations_1.setValueForStyles(getNode(this), styleUpdates, this); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {object} context */ _updateDOMChildren: function (lastProps, nextProps, transaction, context) { var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); { setAndValidateContentChildDev.call(this, nextContent); } } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { this.updateMarkup('' + nextHtml); } { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } else if (nextChildren != null) { { setAndValidateContentChildDev.call(this, null); } this.updateChildren(nextChildren, transaction, context); } }, getHostNode: function () { return getNode(this); }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function (safely, skipLifecycle) { switch (this._tag) { case 'audio': case 'form': case 'iframe': case 'img': case 'image': case 'link': case 'object': case 'source': case 'video': var listeners = this._wrapperState.listeners; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].remove(); } } break; case 'input': case 'textarea': inputValueTracking_1.stopTracking(this); break; case 'html': case 'head': case 'body': /** * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. */ invariant_1(false, '<%s> tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.', this._tag); break; } this.unmountChildren(safely, skipLifecycle); ReactDOMComponentTree_1.uncacheNode(this); this._rootNodeID = 0; this._domID = 0; this._wrapperState = null; { setAndValidateContentChildDev.call(this, null); } }, restoreControlledState: function () { switch (this._tag) { case 'input': ReactDOMInput_1.restoreControlledState(this); return; case 'textarea': ReactDOMTextarea_1.restoreControlledState(this); return; case 'select': ReactDOMSelect_1.restoreControlledState(this); return; } }, getPublicInstance: function () { return getNode(this); } }; index(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild_1); var ReactDOMComponent_1 = ReactDOMComponent; var ReactDOMEmptyComponent = function (instantiate) { // ReactCompositeComponent uses this: this._currentElement = null; // ReactDOMComponentTree uses these: this._hostNode = null; this._hostParent = null; this._hostContainerInfo = null; this._domID = 0; }; index(ReactDOMEmptyComponent.prototype, { mountComponent: function (transaction, hostParent, hostContainerInfo, context) { var domID = hostContainerInfo._idCounter++; this._domID = domID; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var nodeValue = ' react-empty: ' + this._domID + ' '; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var node = ownerDocument.createComment(nodeValue); ReactDOMComponentTree_1.precacheNode(this, node); return DOMLazyTree_1(node); } else { if (transaction.renderToStaticMarkup) { // Normally we'd insert a comment node, but since this is a situation // where React won't take over (static pages), we can simply return // nothing. return ''; } return '<!--' + nodeValue + '-->'; } }, receiveComponent: function () {}, getHostNode: function () { return ReactDOMComponentTree_1.getNodeFromInstance(this); }, unmountComponent: function () { ReactDOMComponentTree_1.uncacheNode(this); } }); var ReactDOMEmptyComponent_1 = ReactDOMEmptyComponent; var COMMENT_NODE$1 = HTMLNodeType_1.COMMENT_NODE; /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings between comment nodes so that they * can undergo the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function (text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // ReactDOMComponentTree uses these: this._hostNode = null; this._hostParent = null; // Properties this._domID = 0; this._mountIndex = 0; this._closingComment = null; this._commentNodes = null; }; index(ReactDOMTextComponent.prototype, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { { var parentInfo; if (hostParent != null) { parentInfo = hostParent._ancestorInfo; } else if (hostContainerInfo != null) { parentInfo = hostContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting_1(null, this._stringText, this, parentInfo); } } var domID = hostContainerInfo._idCounter++; var openingValue = ' react-text: ' + domID + ' '; var closingValue = ' /react-text '; this._domID = domID; this._hostParent = hostParent; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var openingComment = ownerDocument.createComment(openingValue); var closingComment = ownerDocument.createComment(closingValue); var lazyTree = DOMLazyTree_1(ownerDocument.createDocumentFragment()); DOMLazyTree_1.queueChild(lazyTree, DOMLazyTree_1(openingComment)); if (this._stringText) { DOMLazyTree_1.queueChild(lazyTree, DOMLazyTree_1(ownerDocument.createTextNode(this._stringText))); } DOMLazyTree_1.queueChild(lazyTree, DOMLazyTree_1(closingComment)); ReactDOMComponentTree_1.precacheNode(this, openingComment); this._closingComment = closingComment; return lazyTree; } else { var escapedText = escapeTextContentForBrowser_1(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this between comment nodes for the reasons stated // above, but since this is a situation where React won't take over // (static pages), we can simply return the text as it is. return escapedText; } return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->'; } }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function (nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var commentNodes = this.getHostNode(); DOMChildrenOperations_1.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText); } } }, getHostNode: function () { var hostNode = this._commentNodes; if (hostNode) { return hostNode; } if (!this._closingComment) { var openingComment = ReactDOMComponentTree_1.getNodeFromInstance(this); var node = openingComment.nextSibling; while (true) { !(node != null) ? invariant_1(false, 'Missing closing comment for text component %s', this._domID) : void 0; if (node.nodeType === COMMENT_NODE$1 && node.nodeValue === ' /react-text ') { this._closingComment = node; break; } node = node.nextSibling; } } hostNode = [this._hostNode, this._closingComment]; this._commentNodes = hostNode; return hostNode; }, unmountComponent: function () { this._closingComment = null; this._commentNodes = null; ReactDOMComponentTree_1.uncacheNode(this); } }); var ReactDOMTextComponent_1 = ReactDOMTextComponent; var RESET_BATCHED_UPDATES = { initialize: emptyFunction_1, close: function () { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction_1, close: ReactUpdates_1.flushBatchedUpdates.bind(ReactUpdates_1) }; var TRANSACTION_WRAPPERS$2 = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } index(ReactDefaultBatchingStrategyTransaction.prototype, Transaction, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS$2; } }); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { return callback(a, b, c, d, e); } else { return transaction.perform(callback, null, a, b, c, d, e); } } }; var ReactDefaultBatchingStrategy_1 = ReactDefaultBatchingStrategy; function validateCallback(callback) { invariant_1(!callback || typeof callback === 'function', 'Invalid argument passed as callback. Expected a function. Instead ' + 'received: %s', callback); } var validateCallback_1 = validateCallback; function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class CallbackQueue * @implements PooledClass * @internal */ var CallbackQueue = function () { function CallbackQueue(arg) { _classCallCheck$1(this, CallbackQueue); this._callbacks = null; this._contexts = null; this._arg = arg; } /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ CallbackQueue.prototype.enqueue = function enqueue(callback, context) { this._callbacks = this._callbacks || []; this._callbacks.push(callback); this._contexts = this._contexts || []; this._contexts.push(context); }; /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ CallbackQueue.prototype.notifyAll = function notifyAll() { var callbacks = this._callbacks; var contexts = this._contexts; var arg = this._arg; if (callbacks && contexts) { !(callbacks.length === contexts.length) ? invariant_1(false, 'Mismatched list of contexts in callback queue') : void 0; this._callbacks = null; this._contexts = null; for (var i = 0; i < callbacks.length; i++) { validateCallback_1(callbacks[i]); callbacks[i].call(contexts[i], arg); } callbacks.length = 0; contexts.length = 0; } }; CallbackQueue.prototype.checkpoint = function checkpoint() { return this._callbacks ? this._callbacks.length : 0; }; CallbackQueue.prototype.rollback = function rollback(len) { if (this._callbacks && this._contexts) { this._callbacks.length = len; this._contexts.length = len; } }; /** * Resets the internal queue. * * @internal */ CallbackQueue.prototype.reset = function reset() { this._callbacks = null; this._contexts = null; }; /** * `PooledClass` looks for this. */ CallbackQueue.prototype.destructor = function destructor() { this.reset(); }; return CallbackQueue; }(); var CallbackQueue_1 = PooledClass_1.addPoolingTo(CallbackQueue); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection_1.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection_1.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function () { var currentlyEnabled = ReactBrowserEventEmitter_1.isEnabled(); ReactBrowserEventEmitter_1.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` * restores the previous value. */ close: function (previouslyEnabled) { ReactBrowserEventEmitter_1.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function () { this.reactMountReady.notifyAll(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS$3 = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; { TRANSACTION_WRAPPERS$3.push({ initialize: ReactInstrumentation.debugTool.onBeginFlush, close: ReactInstrumentation.debugTool.onEndFlush }); } /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction(useCreateElement) { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactDOMTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue_1.getPooled(null); this.useCreateElement = useCreateElement; } var Mixin$1 = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS$3; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * @return {object} The queue to collect React async events. */ getUpdateQueue: function () { return ReactUpdateQueue_1; }, /** * Save current transaction state -- if the return value from this method is * passed to `rollback`, the transaction will be reset to that state. */ checkpoint: function () { // reactMountReady is the our only stateful wrapper return this.reactMountReady.checkpoint(); }, rollback: function (checkpoint) { this.reactMountReady.rollback(checkpoint); }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue_1.release(this.reactMountReady); this.reactMountReady = null; } }; index(ReactReconcileTransaction.prototype, Transaction, Mixin$1); PooledClass_1.addPoolingTo(ReactReconcileTransaction); var ReactReconcileTransaction_1 = ReactReconcileTransaction; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule findDOMNode * */ var ELEMENT_NODE$3 = HTMLNodeType_1.ELEMENT_NODE; var ReactCurrentOwner$3 = ReactGlobalSharedState_1.ReactCurrentOwner; var findFiber = function (arg) { invariant_1(false, 'Missing injection for fiber findDOMNode'); }; var findStack = function (arg) { invariant_1(false, 'Missing injection for stack findDOMNode'); }; var findDOMNode = function (componentOrElement) { { var owner = ReactCurrentOwner$3.current; if (owner !== null) { var isFiber = typeof owner.tag === 'number'; var warnedAboutRefsInRender = isFiber ? owner.stateNode._warnedAboutRefsInRender : owner._warnedAboutRefsInRender; warning_1(warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName_1(owner) || 'A component'); if (isFiber) { owner.stateNode._warnedAboutRefsInRender = true; } else { owner._warnedAboutRefsInRender = true; } } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === ELEMENT_NODE$3) { return componentOrElement; } var inst = ReactInstanceMap_1.get(componentOrElement); if (inst) { if (typeof inst.tag === 'number') { return findFiber(inst); } else { return findStack(inst); } } if (typeof componentOrElement.render === 'function') { invariant_1(false, 'Unable to find node on an unmounted component.'); } else { invariant_1(false, 'Element appears to be neither ReactComponent nor DOMNode. Keys: %s', Object.keys(componentOrElement)); } }; findDOMNode._injectFiber = function (fn) { findFiber = fn; }; findDOMNode._injectStack = function (fn) { findStack = fn; }; var findDOMNode_1 = findDOMNode; function getHostComponentFromComposite(inst) { var type; while ((type = inst._renderedNodeType) === ReactNodeTypes_1.COMPOSITE) { inst = inst._renderedComponent; } if (type === ReactNodeTypes_1.HOST) { return inst._renderedComponent; } else if (type === ReactNodeTypes_1.EMPTY) { return null; } } var getHostComponentFromComposite_1 = getHostComponentFromComposite; var alreadyInjected$1 = false; function inject$1() { if (alreadyInjected$1) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected$1 = true; ReactGenericBatching_1.injection.injectStackBatchedUpdates(ReactUpdates_1.batchedUpdates); ReactHostComponent_1.injection.injectGenericComponentClass(ReactDOMComponent_1); ReactHostComponent_1.injection.injectTextComponentClass(ReactDOMTextComponent_1); ReactEmptyComponent_1.injection.injectEmptyComponentFactory(function (instantiate) { return new ReactDOMEmptyComponent_1(instantiate); }); ReactUpdates_1.injection.injectReconcileTransaction(ReactReconcileTransaction_1); ReactUpdates_1.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy_1); ReactComponentEnvironment_1.injection.injectEnvironment(ReactComponentBrowserEnvironment_1); findDOMNode_1._injectStack(function (inst) { inst = getHostComponentFromComposite_1(inst); return inst ? ReactDOMComponentTree_1.getNodeFromInstance(inst) : null; }); } var ReactDOMStackInjection = { inject: inject$1 }; var DOCUMENT_NODE$1 = HTMLNodeType_1.DOCUMENT_NODE; function ReactDOMContainerInfo(topLevelWrapper, node) { var info = { _topLevelWrapper: topLevelWrapper, _idCounter: 1, _ownerDocument: node ? node.nodeType === DOCUMENT_NODE$1 ? node : node.ownerDocument : null, _node: node, _tag: node ? node.nodeName.toLowerCase() : null, _namespaceURI: node ? node.namespaceURI : null }; { info._ancestorInfo = node ? validateDOMNesting_1.updatedAncestorInfo(null, info._tag, null) : null; } return info; } var ReactDOMContainerInfo_1 = ReactDOMContainerInfo; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule adler32 * */ var MOD = 65521; // adler32 is not cryptographically strong, and is only used to sanity check that // markup generated on the server matches the markup generated on the client. // This implementation (a modified version of the SheetJS version) has been optimized // for our use case, at the expense of conforming to the adler32 specification // for non-ascii inputs. function adler32(data) { var a = 1; var b = 0; var i = 0; var l = data.length; var m = l & ~0x3; while (i < m) { var n = Math.min(i + 4096, m); for (; i < n; i += 4) { b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); } a %= MOD; b %= MOD; } for (; i < l; i++) { b += a += data.charCodeAt(i); } a %= MOD; b %= MOD; return a | b << 16; } var adler32_1 = adler32; var TAG_END = /\/?>/; var COMMENT_START = /^<\!\-\-/; var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function (markup) { var checksum = adler32_1(markup); // Add checksum (handle both parent tags, comments and self-closing tags) if (COMMENT_START.test(markup)) { return markup; } else { return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); } }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function (markup, element) { var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32_1(markup); return markupChecksum === existingChecksum; } }; var ReactMarkupChecksum_1 = ReactMarkupChecksum; /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerBatchingStrategy */ var ReactServerBatchingStrategy = { isBatchingUpdates: false, batchedUpdates: function (callback) { // Don't do anything here. During the server rendering we don't want to // schedule any updates. We will simply ignore them. } }; var ReactServerBatchingStrategy_1 = ReactServerBatchingStrategy; var pendingTransactions = 0; /** * @param {ReactElement} element * @return {string} the HTML markup */ function renderToStringImpl(element, makeStaticMarkup) { var transaction; var previousBatchingStrategy; try { previousBatchingStrategy = ReactUpdates_1.injection.getBatchingStrategy(); ReactUpdates_1.injection.injectBatchingStrategy(ReactServerBatchingStrategy_1); transaction = ReactServerRenderingTransaction_1.getPooled(makeStaticMarkup); pendingTransactions++; return transaction.perform(function () { var componentInstance = instantiateReactComponent_1(element, true); var markup = ReactReconciler_1.mountComponent(componentInstance, transaction, null, ReactDOMContainerInfo_1(), emptyObject_1, 0 /* parentDebugID */ ); { ReactInstrumentation.debugTool.onUnmountComponent(componentInstance._debugID); } if (!makeStaticMarkup) { markup = ReactMarkupChecksum_1.addChecksumToMarkup(markup); } return markup; }, null); } finally { pendingTransactions--; ReactServerRenderingTransaction_1.release(transaction); // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. if (!pendingTransactions) { ReactUpdates_1.injection.injectBatchingStrategy(previousBatchingStrategy); } } } /** * Render a ReactElement to its initial HTML. This should only be used on the * server. * See https://facebook.github.io/react/docs/react-dom-server.html#rendertostring */ function renderToString(element) { !React.isValidElement(element) ? invariant_1(false, 'renderToString(): You must pass a valid ReactElement.') : void 0; return renderToStringImpl(element, false); } /** * Similar to renderToString, except this doesn't create extra DOM attributes * such as data-react-id that React uses internally. * See https://facebook.github.io/react/docs/react-dom-server.html#rendertostaticmarkup */ function renderToStaticMarkup(element) { !React.isValidElement(element) ? invariant_1(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : void 0; return renderToStringImpl(element, true); } var ReactServerRendering = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactVersion */ var ReactVersion = '16.0.0-alpha.11'; ReactDOMInjection.inject(); ReactDOMStackInjection.inject(); var ReactDOMServer = { renderToString: ReactServerRendering.renderToString, renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, version: ReactVersion }; var ReactDOMServer_1 = ReactDOMServer; return ReactDOMServer_1; })));
dist/react-google-calendar-events-list.es.js
VinSpee/react-gcal-events-list
import React from 'react'; 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 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 GET_CAL_URL = function GET_CAL_URL(calID, key) { return 'https://www.googleapis.com/calendar/v3/calendars/' + calID + '/events?fields=items(summary,id,location,start)&key=' + key; }; var formatTime = function formatTime(time) { time = time.substring(0, time.length - 6); // eslint-disable-line var parts = time.split(':'); var hour = parts[0]; var minutes = parts[1]; if (hour > 12) { return time = hour - 12 + ':' + minutes + 'PM'; // eslint-disable-line } else if (hour === 0) { return time = 12 + ':' + minutes + 'AM'; // eslint-disable-line } else if (hour === 12) { return time += 'PM'; // eslint-disable-line } return time += 'AM'; // eslint-disable-line }; var formatDate = function formatDate(date) { date = date.split('-'); // eslint-disable-line var eventYear = date.shift(); date.push(eventYear); date = date.join('/'); // eslint-disable-line return date; }; var Calendar = function (_React$PureComponent) { inherits(Calendar, _React$PureComponent); function Calendar() { var _ref4; var _temp, _this, _ret; classCallCheck(this, Calendar); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref4 = Calendar.__proto__ || Object.getPrototypeOf(Calendar)).call.apply(_ref4, [this].concat(args))), _this), _this.state = { loading: false, events: [] }, _this.getEvents = function () { _this.setState(function (state) { return Object.assign({}, state, { events: [], loading: true }); }); return fetch(GET_CAL_URL(_this.props.calendarID, _this.props.apiKey)).then(function (res) { return res.json(); }); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(Calendar, [{ key: 'componentDidMount', value: function componentDidMount() { var _this2 = this; this.getEvents().then(function (data) { _this2.setState(function (state) { var _ref; return Object.assign({}, state, { loading: false, events: (_ref = data) != null ? _ref.items : _ref }); }); }); } }, { key: 'render', value: function render() { var children = this.props.children; var _state = this.state, _state$loading = _state.loading, loading = _state$loading === undefined ? false : _state$loading, _state$events = _state.events, events = _state$events === undefined ? [] : _state$events; var currentEvents = events.filter(function (event) { var _ref2, _ref3; return (((_ref2 = event) != null ? (_ref2 = _ref2.start) != null ? _ref2.dateTime : _ref2 : _ref2) || ((_ref3 = event) != null ? (_ref3 = _ref3.start) != null ? _ref3.date : _ref3 : _ref3)) > new Date().toISOString(); }); if (children && typeof children === 'function') { return children({ events: currentEvents, loading: loading }); } return React.createElement( 'div', { className: 'events' }, React.createElement( 'dl', { className: 'events__list' }, currentEvents.map(function (event) { return React.createElement( 'div', { key: event.id, className: 'event' }, React.createElement( 'dt', { 'data-test': 'event-summary', className: 'event__title' }, event.summary ), event.location && React.createElement( 'span', { className: 'event__location' }, React.createElement( 'span', null, event.location ) ), React.createElement( 'dd', { className: 'event__details' }, React.createElement( 'time', { className: 'event__schedule', dateTime: event.start.dateTime || event.start.date }, React.createElement( 'span', { className: 'event__date' }, event.start.dateTime ? formatDate(event.start.dateTime.split('T')[0]) : formatDate(event.start.date) ), event.start.dateTime && React.createElement( 'span', { className: 'event__time' }, formatTime(event.start.dateTime.split('T')[1]) ) ) ) ); }) ) ); } }]); return Calendar; }(React.PureComponent); export default Calendar;
src/components/NewFolderSetup.js
robshox/boostv1
import React from 'react'; import ReactDOM from 'react-dom'; import { addFolder } from '../actions'; import { connect } from 'react-redux'; const mapStateToProps = ({ addingFolder, folders }) => ({ folders, addingFolder }); const mapDispatchToProps = dispatch => ({ addFolder: name => dispatch(addFolder(name)) }); const NewFolderSetup = React.createClass({ render(){ return( <div className="col-sm-12"> <input type="text" className="form-control input-lg" ref='addFolder' placeholder="Enter Folder Name"/> <button onClick={this.createFolder} data-dismiss="modal" className="btn col-xs-12 btn-lg text-center btn-primary m-b m-t">Create Folder</button> </div>); }, createFolder(evt) { var name = ReactDOM.findDOMNode(this.refs.addFolder).value; this.props.addFolder(name); console.log(name); } }); export default connect(mapStateToProps, mapDispatchToProps)(NewFolderSetup);
go-betz/src/components/AuthenticatedRoute/index.js
FabioFischer/go-betz
import React from 'react'; import { Route, Redirect } from 'react-router-dom' import { ls } from './../../services'; const AuthenticatedRoute = ({ component: Component, ...rest }) => { const renderMethod = props => { const currentUser = ls.get('current_user'); if (!currentUser) { alert('Não autorizado! 🤦🏻‍♂️'); return (<Redirect to={{ pathname: 'sign-in', state: { from: props.location } }} />); }; return (<Component {...props} />) }; return ( <Route {...rest} render={props => renderMethod(props)} /> ); }; export default AuthenticatedRoute;
node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-hot-loader/webpack.config.js
kaguillera/newspipeline
// For instructions about this file refer to // webpack and webpack-hot-middleware documentation var webpack = require('webpack'); var path = require('path'); module.exports = { debug: true, devtool: '#eval-source-map', context: path.join(__dirname, 'app', 'js'), entry: [ 'webpack/hot/dev-server', 'webpack-hot-middleware/client', './main' ], output: { path: path.join(__dirname, 'app', 'js'), publicPath: '/js/', filename: 'bundle.js' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'] } ] } };
frontend/jqwidgets/jqwidgets-react/react_jqxchart.js
liamray/nexl-js
/* jQWidgets v5.7.2 (2018-Apr) Copyright (c) 2011-2018 jQWidgets. License: https://jqwidgets.com/license/ */ import React from 'react'; const JQXLite = window.JQXLite; export const jqx = window.jqx; export default class JqxChart extends React.Component { componentDidMount() { let options = this.manageAttributes(); this.createComponent(options); }; manageAttributes() { let properties = ['title','description','source','showBorderLine','borderLineColor','borderLineWidth','backgroundColor','backgroundImage','showLegend','legendLayout','categoryAxis','padding','titlePadding','colorScheme','greyScale','showToolTips','toolTipShowDelay','toolTipHideDelay','toolTipMoveDuration','drawBefore','draw','rtl','enableCrosshairs','crosshairsColor','crosshairsDashStyle','crosshairsLineWidth','columnSeriesOverlap','enabled','enableAnimations','animationDuration','enableAxisTextAnimation','renderEngine','xAxis','valueAxis','seriesGroups']; let options = {}; for(let item in this.props) { if(item === 'settings') { for(let itemTwo in this.props[item]) { options[itemTwo] = this.props[item][itemTwo]; } } else { if(properties.indexOf(item) !== -1) { options[item] = this.props[item]; } } } return options; }; createComponent(options) { if(!this.style) { for (let style in this.props.style) { JQXLite(this.componentSelector).css(style, this.props.style[style]); } } if(this.props.className !== undefined) { let classes = this.props.className.split(' '); for (let i = 0; i < classes.length; i++ ) { JQXLite(this.componentSelector).addClass(classes[i]); } } if(!this.template) { JQXLite(this.componentSelector).html(this.props.template); } JQXLite(this.componentSelector).jqxChart(options); }; setOptions(options) { JQXLite(this.componentSelector).jqxChart('setOptions', options); }; getOptions() { if(arguments.length === 0) { throw Error('At least one argument expected in getOptions()!'); } let resultToReturn = {}; for(let i = 0; i < arguments.length; i++) { resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxChart(arguments[i]); } return resultToReturn; }; on(name,callbackFn) { JQXLite(this.componentSelector).on(name,callbackFn); }; off(name) { JQXLite(this.componentSelector).off(name); }; title(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('title', arg) } else { return JQXLite(this.componentSelector).jqxChart('title'); } }; description(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('description', arg) } else { return JQXLite(this.componentSelector).jqxChart('description'); } }; source(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('source', arg) } else { return JQXLite(this.componentSelector).jqxChart('source'); } }; showBorderLine(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('showBorderLine', arg) } else { return JQXLite(this.componentSelector).jqxChart('showBorderLine'); } }; borderLineColor(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('borderLineColor', arg) } else { return JQXLite(this.componentSelector).jqxChart('borderLineColor'); } }; borderLineWidth(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('borderLineWidth', arg) } else { return JQXLite(this.componentSelector).jqxChart('borderLineWidth'); } }; backgroundColor(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('backgroundColor', arg) } else { return JQXLite(this.componentSelector).jqxChart('backgroundColor'); } }; backgroundImage(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('backgroundImage', arg) } else { return JQXLite(this.componentSelector).jqxChart('backgroundImage'); } }; showLegend(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('showLegend', arg) } else { return JQXLite(this.componentSelector).jqxChart('showLegend'); } }; legendLayout(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('legendLayout', arg) } else { return JQXLite(this.componentSelector).jqxChart('legendLayout'); } }; categoryAxis(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('categoryAxis', arg) } else { return JQXLite(this.componentSelector).jqxChart('categoryAxis'); } }; padding(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('padding', arg) } else { return JQXLite(this.componentSelector).jqxChart('padding'); } }; titlePadding(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('titlePadding', arg) } else { return JQXLite(this.componentSelector).jqxChart('titlePadding'); } }; colorScheme(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('colorScheme', arg) } else { return JQXLite(this.componentSelector).jqxChart('colorScheme'); } }; greyScale(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('greyScale', arg) } else { return JQXLite(this.componentSelector).jqxChart('greyScale'); } }; showToolTips(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('showToolTips', arg) } else { return JQXLite(this.componentSelector).jqxChart('showToolTips'); } }; toolTipShowDelay(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('toolTipShowDelay', arg) } else { return JQXLite(this.componentSelector).jqxChart('toolTipShowDelay'); } }; toolTipHideDelay(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('toolTipHideDelay', arg) } else { return JQXLite(this.componentSelector).jqxChart('toolTipHideDelay'); } }; toolTipMoveDuration(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('toolTipMoveDuration', arg) } else { return JQXLite(this.componentSelector).jqxChart('toolTipMoveDuration'); } }; drawBefore(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('drawBefore', arg) } else { return JQXLite(this.componentSelector).jqxChart('drawBefore'); } }; draw(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('draw', arg) } else { return JQXLite(this.componentSelector).jqxChart('draw'); } }; rtl(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('rtl', arg) } else { return JQXLite(this.componentSelector).jqxChart('rtl'); } }; enableCrosshairs(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('enableCrosshairs', arg) } else { return JQXLite(this.componentSelector).jqxChart('enableCrosshairs'); } }; crosshairsColor(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('crosshairsColor', arg) } else { return JQXLite(this.componentSelector).jqxChart('crosshairsColor'); } }; crosshairsDashStyle(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('crosshairsDashStyle', arg) } else { return JQXLite(this.componentSelector).jqxChart('crosshairsDashStyle'); } }; crosshairsLineWidth(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('crosshairsLineWidth', arg) } else { return JQXLite(this.componentSelector).jqxChart('crosshairsLineWidth'); } }; columnSeriesOverlap(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('columnSeriesOverlap', arg) } else { return JQXLite(this.componentSelector).jqxChart('columnSeriesOverlap'); } }; enabled(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('enabled', arg) } else { return JQXLite(this.componentSelector).jqxChart('enabled'); } }; enableAnimations(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('enableAnimations', arg) } else { return JQXLite(this.componentSelector).jqxChart('enableAnimations'); } }; animationDuration(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('animationDuration', arg) } else { return JQXLite(this.componentSelector).jqxChart('animationDuration'); } }; enableAxisTextAnimation(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('enableAxisTextAnimation', arg) } else { return JQXLite(this.componentSelector).jqxChart('enableAxisTextAnimation'); } }; renderEngine(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('renderEngine', arg) } else { return JQXLite(this.componentSelector).jqxChart('renderEngine'); } }; xAxis(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('xAxis', arg) } else { return JQXLite(this.componentSelector).jqxChart('xAxis'); } }; valueAxis(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('valueAxis', arg) } else { return JQXLite(this.componentSelector).jqxChart('valueAxis'); } }; seriesGroups(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxChart('seriesGroups', arg) } else { return JQXLite(this.componentSelector).jqxChart('seriesGroups'); } }; getInstance() { return JQXLite(this.componentSelector).jqxChart('getInstance'); }; refresh() { return JQXLite(this.componentSelector).jqxChart('refresh'); }; update() { return JQXLite(this.componentSelector).jqxChart('update'); }; destroy() { return JQXLite(this.componentSelector).jqxChart('destroy'); }; addColorScheme(schemeName, colors) { return JQXLite(this.componentSelector).jqxChart('addColorScheme', schemeName, colors); }; removeColorScheme(schemeName) { return JQXLite(this.componentSelector).jqxChart('removeColorScheme', schemeName); }; getItemsCount(groupIndex, serieIndex) { return JQXLite(this.componentSelector).jqxChart('getItemsCount', groupIndex, serieIndex); }; getItemCoord(groupIndex, serieIndex, itemIndex) { return JQXLite(this.componentSelector).jqxChart('getItemCoord', groupIndex, serieIndex, itemIndex); }; getXAxisRect(groupIndex) { return JQXLite(this.componentSelector).jqxChart('getXAxisRect', groupIndex); }; getXAxisLabels(groupIndex) { return JQXLite(this.componentSelector).jqxChart('getXAxisLabels', groupIndex); }; getValueAxisRect(groupIndex) { return JQXLite(this.componentSelector).jqxChart('getValueAxisRect', groupIndex); }; getValueAxisLabels(groupIndex) { return JQXLite(this.componentSelector).jqxChart('getValueAxisLabels', groupIndex); }; getColorScheme(colorScheme) { return JQXLite(this.componentSelector).jqxChart('getColorScheme', colorScheme); }; hideSerie(groupIndex, serieIndex, itemIndex) { return JQXLite(this.componentSelector).jqxChart('hideSerie', groupIndex, serieIndex, itemIndex); }; showSerie(groupIndex, serieIndex, itemIndex) { return JQXLite(this.componentSelector).jqxChart('showSerie', groupIndex, serieIndex, itemIndex); }; hideToolTip(hideDelay) { return JQXLite(this.componentSelector).jqxChart('hideToolTip', hideDelay); }; showToolTip(groupIndex, serieIndex, itemIndex, showDelay, hideDelay) { return JQXLite(this.componentSelector).jqxChart('showToolTip', groupIndex, serieIndex, itemIndex, showDelay, hideDelay); }; saveAsJPEG(fileName, exportServerUrl) { return JQXLite(this.componentSelector).jqxChart('saveAsJPEG', fileName, exportServerUrl); }; saveAsPNG(fileName, exportServerUrl) { return JQXLite(this.componentSelector).jqxChart('saveAsPNG', fileName, exportServerUrl); }; saveAsPDF(fileName, exportServerUrl) { return JQXLite(this.componentSelector).jqxChart('saveAsPDF', fileName, exportServerUrl); }; getXAxisValue(offset, groupIndex) { return JQXLite(this.componentSelector).jqxChart('getXAxisValue', offset, groupIndex); }; getValueAxisValue(offset, groupIndex) { return JQXLite(this.componentSelector).jqxChart('getValueAxisValue', offset, groupIndex); }; render() { let id = 'jqxChart' + JQXLite.generateID(); this.componentSelector = '#' + id; return ( <div id={id}>{this.props.value}{this.props.children}</div> ) }; };
Realization/frontend/czechidm-acc/src/content/system/SystemSynchronizationLogDetail.js
bcvsolutions/CzechIdMng
import PropTypes from 'prop-types'; import React from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; // import { Basic, Domain, Managers, Utils, Advanced } from 'czechidm-core'; import { SynchronizationLogManager, SyncActionLogManager} from '../../redux'; import SynchronizationActionTypeEnum from '../../domain/SynchronizationActionTypeEnum'; import OperationResultTypeEnum from '../../domain/OperationResultTypeEnum'; const uiKey = 'system-synchronization-log'; const uiKeyLogs = 'system-synchronization-action-logs'; const synchronizationLogManager = new SynchronizationLogManager(); const syncActionLogManager = new SyncActionLogManager(); class SystemSynchronizationLogDetail extends Advanced.AbstractTableContent { constructor(props, context) { super(props, context); this.state = { ...this.state }; } getManager() { return synchronizationLogManager; } getUiKey() { return uiKey; } getContentKey() { return 'acc:content.system.systemSynchronizationLogDetail'; } showDetail(entity) { const {entityId} = this.props.match.params; this.context.history.push(`/system/${entityId}/synchronization-action-logs/${entity.id}/detail`); } // @Deprecated - since V10 ... replaced by dynamic key in Route // UNSAFE_componentWillReceiveProps(nextProps) { // const { logId} = nextProps.match.params; // if (logId && logId !== this.props.match.params.logId) { // this._initComponent(nextProps); // } // } // Did mount only call initComponent method componentDidMount() { this._initComponent(this.props); } /** * Method for init component from didMount method and from willReceiveProps method * @param {properties of component} props For didmount call is this.props for call from willReceiveProps is nextProps. */ _initComponent(props) { const {logId} = props.match.params; this.context.store.dispatch(synchronizationLogManager.fetchEntity(logId)); this.selectNavigationItems(['sys-systems', 'system-synchronization-configs']); } render() { const { _showLoading, _synchronizationLog} = this.props; const forceSearchParameters = new Domain.SearchParameters() .setFilter('synchronizationLogId', _synchronizationLog ? _synchronizationLog.id : Domain.SearchParameters.BLANK_UUID); const synchronizationLog = _synchronizationLog; return ( <div> <Helmet title={this.i18n('title')} /> <Basic.Confirm ref="confirm-delete" level="danger"/> <Basic.ContentHeader> <span dangerouslySetInnerHTML={{ __html: this.i18n('header') }}/> </Basic.ContentHeader> <Basic.Panel className="no-border"> <Basic.AbstractForm readOnly ref="form" data={synchronizationLog} showLoading={_showLoading}> <Basic.Checkbox ref="running" label={this.i18n('acc:entity.SynchronizationLog.running')}/> <Basic.Checkbox ref="containsError" label={this.i18n('acc:entity.SynchronizationLog.containsError')}/> <Basic.DateTimePicker ref="started" label={this.i18n('acc:entity.SynchronizationLog.started')}/> <Basic.DateTimePicker ref="ended" label={this.i18n('acc:entity.SynchronizationLog.ended')}/> <Basic.TextField ref="token" label={this.i18n('acc:entity.SynchronizationLog.token')}/> <Basic.ScriptArea ref="log" mode="sqlserver" height="30em" label={this.i18n('acc:entity.SyncItemLog.log')}/> </Basic.AbstractForm> <Basic.PanelFooter> <Basic.Button type="button" level="link" onClick={this.context.history.goBack} showLoading={_showLoading}> {this.i18n('button.back')} </Basic.Button> </Basic.PanelFooter> </Basic.Panel> <Basic.ContentHeader rendered={synchronizationLog} style={{ marginBottom: 0 }}> <Basic.Icon value="transfer"/> {' '} <span dangerouslySetInnerHTML={{ __html: this.i18n('syncActionLogsHeader') }}/> </Basic.ContentHeader> <Basic.Panel rendered={synchronizationLog} className="no-border"> <Advanced.Table ref="table" uiKey={uiKeyLogs} manager={syncActionLogManager} forceSearchParameters={forceSearchParameters} showRowSelection={Managers.SecurityManager.hasAnyAuthority(['SYSTEM_UPDATE'])} > <Advanced.Column property="" header="" className="detail-button" cell={ ({ rowIndex, data }) => { return ( <Advanced.DetailButton title={this.i18n('button.detail')} onClick={this.showDetail.bind(this, data[rowIndex], false)}/> ); } }/> <Advanced.Column property="syncAction" face="enum" enumClass={SynchronizationActionTypeEnum} header={this.i18n('acc:entity.SyncActionLog.syncAction')} sort/> <Advanced.Column property="operationResult" face="enum" enumClass={OperationResultTypeEnum} header={this.i18n('acc:entity.SyncActionLog.operationResult')} sort/> <Advanced.Column property="operationCount" face="text" header={this.i18n('acc:entity.SyncActionLog.operationCount')} sort/> </Advanced.Table> </Basic.Panel> </div> ); } } SystemSynchronizationLogDetail.propTypes = { _showLoading: PropTypes.bool, }; SystemSynchronizationLogDetail.defaultProps = { _showLoading: false, }; function select(state, component) { const entity = Utils.Entity.getEntity(state, synchronizationLogManager.getEntityType(), component.match.params.logId); return { _synchronizationLog: entity, _showLoading: Utils.Ui.isShowLoading(state, `${uiKey}-detail`), }; } export default connect(select)(SystemSynchronizationLogDetail);
admin/products/ThumbnailField.js
romainquellec/cuistot
import React from 'react'; const ThumbnailField = ({ record }) => <img src={record.thumbnail} style={{ width: 25, maxWidth: 25, maxHeight: 25 }} role="presentation" />; ThumbnailField.defaultProps = { style: { padding: '0 0 0 16px' }, }; export default ThumbnailField;
ui/app/components/Link/Link.js
StamusNetworks/scirius
import React from 'react'; import PropTypes from 'prop-types'; import StyledLink from './StyledLink'; const Link = (props) => <StyledLink {...props}>{props.children}</StyledLink> Link.propTypes = { children: PropTypes.any, } export default Link;
packages/material-ui-icons/src/Timer3Rounded.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M11.61 12.97c-.16-.24-.36-.46-.62-.65-.25-.19-.56-.35-.93-.48.3-.14.57-.3.8-.5.23-.2.42-.41.57-.64.15-.23.27-.46.34-.71.08-.24.11-.49.11-.73 0-.55-.09-1.04-.28-1.46-.18-.42-.44-.77-.78-1.06-.33-.28-.73-.5-1.2-.64-.45-.13-.97-.2-1.53-.2-.55 0-1.06.08-1.52.24-.47.17-.87.4-1.2.69-.33.29-.6.63-.78 1.03-.2.39-.29.83-.29 1.29h1.98c0-.26.05-.49.14-.69.09-.2.22-.38.38-.52.17-.14.36-.25.58-.33s.46-.12.73-.12c.61 0 1.06.16 1.36.47.3.31.44.75.44 1.32 0 .27-.04.52-.12.74-.08.22-.21.41-.38.57s-.38.28-.63.37-.55.13-.89.13H6.72v1.57H7.9c.34 0 .64.04.91.11.27.08.5.19.69.35.19.16.34.36.44.61.1.24.16.54.16.87 0 .62-.18 1.09-.53 1.42-.35.33-.84.49-1.45.49-.29 0-.56-.04-.8-.13-.24-.08-.44-.2-.61-.36s-.3-.34-.39-.56c-.09-.22-.14-.46-.14-.72H4.19c0 .55.11 1.03.32 1.45.21.42.5.77.86 1.05s.77.49 1.24.63.96.21 1.48.21c.57 0 1.09-.08 1.58-.23s.91-.38 1.26-.68c.36-.3.64-.66.84-1.1.2-.43.3-.93.3-1.48 0-.29-.04-.58-.11-.86-.08-.25-.19-.51-.35-.76zm9.26 1.4c-.14-.28-.35-.53-.63-.74-.28-.21-.61-.39-1.01-.53s-.85-.27-1.35-.38c-.35-.07-.64-.15-.87-.23-.23-.08-.41-.16-.55-.25s-.23-.19-.28-.3c-.05-.11-.08-.24-.08-.39s.03-.28.09-.41.15-.25.27-.34c.12-.1.27-.18.45-.24s.4-.09.64-.09c.25 0 .47.04.66.11s.35.17.48.29.22.26.29.42c.06.16.1.32.1.49h1.95c0-.39-.08-.75-.24-1.09s-.39-.63-.69-.88c-.3-.25-.66-.44-1.09-.59-.43-.15-.92-.22-1.46-.22-.51 0-.98.07-1.39.21s-.77.33-1.06.57c-.29.24-.51.52-.67.84s-.23.65-.23 1.01.08.68.23.96.37.52.64.73c.27.21.6.38.98.53.38.14.81.26 1.27.36.39.08.71.17.95.26s.43.19.57.29c.13.1.22.22.27.34.05.12.07.25.07.39 0 .32-.13.57-.4.77s-.66.29-1.17.29c-.22 0-.43-.02-.64-.08-.21-.05-.4-.13-.56-.24-.17-.11-.3-.26-.41-.44-.11-.18-.17-.41-.18-.67h-1.89c0 .36.08.71.24 1.05s.39.65.7.93c.31.27.69.49 1.15.66.46.17.98.25 1.58.25.53 0 1.01-.06 1.44-.19.43-.13.8-.31 1.11-.54.31-.23.54-.51.71-.83.17-.32.25-.67.25-1.06-.02-.4-.09-.74-.24-1.02z" /></g></React.Fragment> , 'Timer3Rounded');
node_modules/reactify/node_modules/react-tools/src/classic/class/__tests__/ReactBind-test.js
mjibson/moggio
/** * 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. * * @emails react-core */ /*global global:true*/ 'use strict'; var mocks = require('mocks'); var React = require('React'); var ReactDoNotBindDeprecated = require('ReactDoNotBindDeprecated'); var ReactTestUtils = require('ReactTestUtils'); var reactComponentExpect = require('reactComponentExpect'); // TODO: Test render and all stock methods. describe('autobinding', function() { it('Holds reference to instance', function() { var mouseDidEnter = mocks.getMockFunction(); var mouseDidLeave = mocks.getMockFunction(); var mouseDidClick = mocks.getMockFunction(); var TestBindComponent = React.createClass({ getInitialState: function() { return {something: 'hi'}; }, onMouseEnter: ReactDoNotBindDeprecated.doNotBind(mouseDidEnter), onMouseLeave: ReactDoNotBindDeprecated.doNotBind(mouseDidLeave), onClick: mouseDidClick, // auto binding only occurs on top level functions in class defs. badIdeas: { badBind: function() { this.state.something; } }, render: function() { return ( <div onMouseOver={this.onMouseEnter.bind(this)} onMouseOut={this.onMouseLeave} onClick={this.onClick} /> ); } }); var instance1 = <TestBindComponent />; var mountedInstance1 = ReactTestUtils.renderIntoDocument(instance1); var rendered1 = reactComponentExpect(mountedInstance1) .expectRenderedChild() .instance(); var instance2 = <TestBindComponent />; var mountedInstance2 = ReactTestUtils.renderIntoDocument(instance2); var rendered2 = reactComponentExpect(mountedInstance2) .expectRenderedChild() .instance(); expect(function() { var badIdea = instance1.badIdeas.badBind; badIdea(); }).toThrow(); expect(mountedInstance1.onMouseEnter).toBe(mountedInstance2.onMouseEnter); expect(mountedInstance1.onMouseLeave).toBe(mountedInstance2.onMouseLeave); expect(mountedInstance1.onClick).not.toBe(mountedInstance2.onClick); ReactTestUtils.Simulate.click(rendered1); expect(mouseDidClick.mock.instances.length).toBe(1); expect(mouseDidClick.mock.instances[0]).toBe(mountedInstance1); ReactTestUtils.Simulate.click(rendered2); expect(mouseDidClick.mock.instances.length).toBe(2); expect(mouseDidClick.mock.instances[1]).toBe(mountedInstance2); ReactTestUtils.Simulate.mouseOver(rendered1); expect(mouseDidEnter.mock.instances.length).toBe(1); expect(mouseDidEnter.mock.instances[0]).toBe(mountedInstance1); ReactTestUtils.Simulate.mouseOver(rendered2); expect(mouseDidEnter.mock.instances.length).toBe(2); expect(mouseDidEnter.mock.instances[1]).toBe(mountedInstance2); ReactTestUtils.Simulate.mouseOut(rendered1); expect(mouseDidLeave.mock.instances.length).toBe(1); expect(mouseDidLeave.mock.instances[0]).toBe(global); ReactTestUtils.Simulate.mouseOut(rendered2); expect(mouseDidLeave.mock.instances.length).toBe(2); expect(mouseDidLeave.mock.instances[1]).toBe(global); }); it('works with mixins', function() { var mouseDidClick = mocks.getMockFunction(); var TestMixin = { onClick: mouseDidClick }; var TestBindComponent = React.createClass({ mixins: [TestMixin], render: function() { return <div onClick={this.onClick} />; } }); var instance1 = <TestBindComponent />; var mountedInstance1 = ReactTestUtils.renderIntoDocument(instance1); var rendered1 = reactComponentExpect(mountedInstance1) .expectRenderedChild() .instance(); ReactTestUtils.Simulate.click(rendered1); expect(mouseDidClick.mock.instances.length).toBe(1); expect(mouseDidClick.mock.instances[0]).toBe(mountedInstance1); }); it('warns if you try to bind to this', function() { spyOn(console, 'warn'); var TestBindComponent = React.createClass({ handleClick: function() { }, render: function() { return <div onClick={this.handleClick.bind(this)} />; } }); ReactTestUtils.renderIntoDocument(<TestBindComponent />) expect(console.warn.argsForCall.length).toBe(1); expect(console.warn.argsForCall[0][0]).toBe( 'Warning: bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See TestBindComponent' ); }); it('does not warn if you pass an auto-bound method to setState', function() { spyOn(console, 'warn'); var TestBindComponent = React.createClass({ getInitialState: function() { return {foo: 1}; }, componentDidMount: function() { this.setState({foo: 2}, this.handleUpdate); }, handleUpdate: function() { }, render: function() { return <div onClick={this.handleClick} />; } }); ReactTestUtils.renderIntoDocument(<TestBindComponent />) expect(console.warn.argsForCall.length).toBe(0); }); });
src/components/UndoRemoveAlert.js
cagedtornado/centralconfig-ui
// React import React, { Component } from 'react'; // The API utils import CentralConfigAPIUtils from '../utils/CentralConfigAPIUtils'; // Actions import ConfigActions from '../actions/ConfigActions'; // The stores import RemovedConfigStore from '../stores/RemovedConfigStore'; class UndoRemoveAlert extends Component { constructor(props){ super(props); // Set initial state: this.state = { removedConfigItem: null }; } componentDidMount() { // Add store listeners ... and notify ME of changes this.undoListener = RemovedConfigStore.addListener(this._onRemoveUpdate); } componentWillUnmount() { // Remove store listeners this.undoListener.remove(); } render() { // If we don't have a removed item, don't show the alert if(this.state.removedConfigItem === null || this.state.removedConfigItem === undefined) { return null; } return ( <div className="alert alert-info" role="alert"> <button type="button" className="close" aria-label="Close" onClick={this._onClearUndo}><span aria-hidden="true">&times;</span></button> Config item <b>{this.state.removedConfigItem.application} / {this.state.removedConfigItem.name}</b> removed - <a className="btn btn-sm btn-outline-primary" onClick={this._undoRemoveClick}>UNDO</a> </div> ); } _onClearUndo = () => { ConfigActions.clearRemovedConfigData(); } _onRemoveUpdate = () => { this.setState({ removedConfigItem: RemovedConfigStore.getConfigItem() }); } _undoRemoveClick = (event) => { // Reset the item and get all items: let APIUtils = new CentralConfigAPIUtils(); APIUtils.setConfigItem(this.state.removedConfigItem).then(() => APIUtils.getAllConfigItems()); } } export default UndoRemoveAlert